Django ValueError:无法对“”使用查询集:对“用户”使用查询集

问题描述 投票:0回答:2

我正在 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)
python django cs50
2个回答
2
投票

您可以通过

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

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

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


0
投票

尝试使用这个,可能会有帮助

  # 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)
© www.soinside.com 2019 - 2024. All rights reserved.