Django ValueError:无法将QuerySet用于"&引用;:对“使用查询集”;“用户”;
我正在CS50w的一个项目中工作,在那里我必须显示我正在跟踪的用户的帖子,我得到了以下错误 ValueError:无法将QuerySet用于“以下内容”:将QuerySet用于“用户” 型号。py:Django ValueError:无法将QuerySet用于"&引用;:对“使用查询集”;“用户”;,django,cs50,Django,Cs50,我正在CS50w的一个项目中工作,在那里我必须显示我正在跟踪的用户的帖子,我得到了以下错误 ValueError:无法将QuerySet用于“以下内容”:将QuerySet用于“用户” 型号。py: class Post(models.Model): """Tracks all the posts""" text = models.TextField(max_length=256) user = models.F
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")
这就是我试图检索以下用户帖子的方式:
视图.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)
非常感谢您的帮助。尝试使用此功能,可能会有所帮助
# 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)
您可以通过反向关系(
followers
)通过Post.user
字段基于字段(followers
)进行筛选:
posts = Post.objects.filter(user__followers__user=request.user)
请参阅Django文档,了解如何使用双下划线分隔模型和字段。谢谢。就是这样。