gpt4 book ai didi

Django休息框架: field name 'likes' is not valid for model 'userPost' improperlyConfigured

转载 作者:行者123 更新时间:2023-12-02 09:19:45 27 4
gpt4 key购买 nike

在我的 Django Rest Framework api 中,我尝试向我的模型 UserPosts 添加一个属性,该属性返回所述帖子的所有喜欢。尽管我尽了最大努力,但我仍然遇到这个错误。下面是我的帖子模型:

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)

这是我喜欢的模型:

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

最后是后序列化器:

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

谢谢。

最佳答案

你至少有三种方法。首先,正如 @WillemVanOnsem 所说,通过 many_to_onelikes 更改为 like_set

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

第二次将模型的属性重命名为 likes 并修复其中的查询集

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

第三,对我来说最简单、最优雅的方法是删除 get_likes 并添加 related_namepost 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()

关于Django休息框架: field name 'likes' is not valid for model 'userPost' improperlyConfigured,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50685103/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com