Django-rest-framework多个url参数

时间:2018-01-01 08:00:59

标签: python django rest django-rest-framework

如何将“示例对象”映射到网址:website.com/api/<user>/<slug>

我得到了这个 invalid literal for int() with base 10: 'username'错误。所以我明白我需要使用用户ID顺序映射到对象,这是因为我能够映射到对象,如果我使用user_id(整数)(url:website.com/api/<user_id>/<slug>)而不是只是用户/用户名(字符串)。

当从user_id(整数)映射到对象到用户(字符串)之类的另一个字段时,有没有办法覆盖默认值?

另外我不明白为什么在(Api View)def get_object中传递用户而不是user_id并不能解决这个问题。

网址

urlpatterns = [
    url(r'^api/(?P<user>\w+)/(?P<slug>[\w-]+)/$', ExampleDetailAPIView.as_view(), name='example'),
]

Api查看

class ExampleDetailAPIView(RetrieveAPIView):
    queryset = Example.objects.all()
    serializer_class = ExampleDetailSerializer

    def get_object(self):
        user = self.kwargs.get('user')
        slug = self.kwargs.get('slug')
        return Example.objects.get(user=user, slug=slug)

    def get_serilizer_context(self, *args, **kwargs):
        return {'request': self.request}

串行

class ExampleDetailSerializer(HyperlinkedModelSerializer):
    url = serializers.SerializerMethodField()

    class Meta:
        model = Example
        fields = [
            'url',
        ]

    def get_url(self, obj):
        request = self.context.get('request')
        return obj.get_api_url(request=request)

模型

class Example(models.Model):
    user                = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    example_name         = models.CharField(max_length=100)
    slug                = models.SlugField(max_length=100, blank=True)

    class Meta:
        unique_together = ('user', 'slug')

    def get_api_url(self, request=None):
        return api_reverse('example-api:example', kwargs={'user': self.user.username, 'slug': self.slug}, request=request)

@receiver(pre_save, sender=Example)
def pre_save_example_slug_receiver(sender, instance, *args, **kwargs):
    slug = slugify(instance.example_name)
    instance.slug = slug

1 个答案:

答案 0 :(得分:0)

您可以在网址中使用for i in range(len(trackers))。为此,您必须首先手动查找用户,然后使用其username查找id对象:

Example