代码之家  ›  专栏  ›  技术社区  ›  yoon

django rest framework:使用url slug查找模型实例,而不是pk(lookup_field,retrieveModelMixin)

  •  0
  • yoon  · 技术社区  · 6 年前

    我想用retrievemodelmixin。 默认设置是使用pk查找,但我想使用另一个模型字段查找模型实例。 那么,我该怎么做呢? 我试图添加 查找_fields='usename' 但它没有成功。

    #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关键字参数调用view profiledetail。修复URL配置,或设置 .lookup_field 视图上的属性正确。

    如何修复此错误? 谢谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Bernhard Vallant    6 年前

    这个 attributes on the view and the serializer 被称为 lookup_field 不是 lookup_fields .