python Django ValueError:无法对“”使用QuerySet:为“用户”使用QuerySet

dtcbnfnu  于 9个月前  发布在  Python
关注(0)|答案(2)|浏览(77)

我在CS50w的一个项目中工作,我必须显示我关注的用户的帖子,我得到了以下错误
ValueError:无法将QuerySet用于“以下内容”:为“用户”使用QuerySet。

models.py:

class Post(models.Model):
    """Tracks all the posts"""
    text = models.TextField(max_length=256)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_posted = models.DateTimeField(auto_now_add=True)

class Following(models.Model):
    """Tracks the following of a user"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers")

这就是我试图检索我所关注的用户的帖子的方式:views.py

# Gets all the posts from the users the current user is following
followings_usernames = Following.objects.filter(user=request.user)
posts = Post.objects.filter(user=followings_usernames)
rm5edbpk

rm5edbpk1#

您可以基于字段(Following.user)通过反向关系(followers)通过Post.user字段进行过滤:

posts = Post.objects.filter(user__followers__user=request.user)

请参阅Django文档了解跨关系的查找以及使用双下划线分隔模型和字段。

093gszye

093gszye2#

试试这个,可能会有帮助

# Gets all the posts from the users the current user is following
    followings_usernames = list(Following.objects.filter(user=request.user).values_list('user', flat=True))
    posts = Post.objects.filter(user__in=followings_usernames)

相关问题