Django Rest Framework:使用url slug,而不是pk查找模型实例(lookup_field,retrievemodelmixin)

时间:2019-02-11 14:13:41

标签: django django-rest-framework

我想使用RetrieveModelMixin。 默认设置是使用pk查找,但是我想查找具有另一个模型字段的模型实例。 那我该怎么办呢? 我试图添加  lookup_fields ='用户名' 但是没有成功。

#models.py
    class Profile(models.Model):
    user       = models.OneToOneField(User, on_delete=models.CASCADE, default='', blank=True, null=False)
    username = models.CharField(max_length=100, blank = False, null = True) 
    post = models.ForeignKey(Post, related_name='post', on_delete=models.CASCADE, null =True)
    introduction = models.TextField()


#serializers.py
    class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'
        lookup_fields = 'username'

#urls.py
    path('test/<slug:username>/', views.ProfileDetail.as_view(),name='profiles-detail'),  


#views.py
    class ProfileDetail(mixins.RetrieveModelMixin,
                 mixins.UpdateModelMixin,
                 mixins.DestroyModelMixin,
                 generics.GenericAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_fields = 'username'

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

此结果

要使用名为“ pk”的URL关键字参数调用的预期视图ProfileDetail。修复您的URL conf,或在视图上正确设置.lookup_field属性。

如何解决此错误? 谢谢。

1 个答案:

答案 0 :(得分:1)

attributes on the view and the serializer被称为lookup_field,而不是lookup_fields