Search code examples
pythondjangocs50

Django ValueError: Cannot use QuerySet for "": Use a QuerySet for "User"


I'm working on a project in CS50w where I have to show the posts of the user I'm following and I'm getting the following error

ValueError: Cannot use QuerySet for "Following": Use a QuerySet for "User".

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")

And this how I'm trying to retrieve the posts of the users I'm following: 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)

Solution

  • You can filter based on a field (Following.user) through a reverse relation (followers) through the Post.user field:

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

    See the Django documentation for lookups that span relationships and the usage of double underscores to separate models and fields.