Django Rest Framework: field name 'likes' is not valid for model 'userPost' improperlyConfigured

时间:2018-06-04 16:37:31

标签: django django-models django-rest-framework

In my Django Rest Framework api I am attempting to add a property to my model UserPosts that returns all likes for said post. Despite my best efforts I keep running into this error. Here is my post model below:

class UserPosts(models.Model):
    userProfile = models.ForeignKey(UserProfile, related_name="posts", on_delete=models.CASCADE)
    image = models.ImageField()
    caption = models.CharField(max_length=240)

    @property
    def get_likes(self):
        from liked.models import Like
        return Like(post=self)

and here is my like model:

class Like(models.Model):
    user = models.OneToOneField(UserProfile, on_delete=models.CASCADE,)
    post = models.ForeignKey(UserPosts, on_delete=models.CASCADE)
    liked_at = models.DateTimeField()

and lastly the post serializer:

class postSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.UserPosts
        fields = ('userProfile', 'image', 'caption', 'likes')

Thanks.

1 个答案:

答案 0 :(得分:1)

you have at least three way, first as sad @Willem Van Onsem, by the many_to_onechange the likes to like_set

class postSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.UserPosts
        fields = ('userProfile', 'image', 'caption', 'like_set')
        #                                             ^^^^^

second rename you model property to likes and fix the queryset inside it

class UserPosts(models.Model):
    userProfile = models.ForeignKey(UserProfile, related_name="posts", on_delete=models.CASCADE)
    image = models.ImageField()
    caption = models.CharField(max_length=240)

    @property
    def likes(self):
    #   ^^^^^
        from liked.models import Like
        return Like.objects.filter(post=self).values() or []
        # solution you try ^^^^^^^
        return self.like_set.values() or []
        # more django way

And Third, for me the most simple and elegant, is to remove your get_likes and add the related_name to the post ForeignKey:

class Like(models.Model):
    user = models.OneToOneField(UserProfile, on_delete=models.CASCADE,)
    post = models.ForeignKey(UserPosts, related_name='likes', on_delete=models.CASCADE)
    #                                    ^^^^^^^^^^^
    liked_at = models.DateTimeField()