0

I have a User Following Django Models system based on one posted here.

How can I get all Post objects of that a user follows, having two models: Post and UserFollowings pointing at User model via ForeignKey but User model not pointing back? I need QuerySet of Posts objects to later call serializer that I have added Posts model

Models:

class User(AbstractUser):
    pass

class Post(models.Model):
    user = models.ForeignKey("User", on_delete=models.CASCADE, related_name='posts')
    body = models.TextField()
    def serialize(self):
        return {
            "id": self.id,
            "author": self.user.first_name +" " + self.user.last_name
        }



class UserFollowing(models.Model):
    user_id = models.ForeignKey("User", on_delete=models.CASCADE, 
                    related_name ='following', null=True)
    following_user_id = models.ForeignKey("User", on_delete=models.CASCADE, 
                    related_name='followers', null=True)
        

I have tried using select_related but I think it cannot work with those models. Basically, I am looking for something like this:

u = User.object.get(id=num)
followers = u.followers 
followers_posts = followers.posts.all()

Last line returns: 'RelatedManager' object has no attribute 'posts'

euh
  • 319
  • 2
  • 11
  • I think what you want is `Post.objects.filter(user__in=u.followers.all())` – sudden_appearance Jul 06 '22 at 11:35
  • `Post.objects.filter(user__followering_following_user_id=u)` – Willem Van Onsem Jul 06 '22 at 11:55
  • thank you for your replies, but @sudden_appearance suggestion returns `ValueError Cannot use QuerySet for "UserFollowing": Use a QuerySet for "User"` and Willem Van Onsem code returned `FieldError Related Field got invalid lookup: followering_following_user_id` (after i changed the `followering` typo) – euh Jul 06 '22 at 14:10

1 Answers1

2

This will return all posts that a user follows

user_instance = User.objects.only('id').get(pk=num)

following_users = UserFollowing.objects.filter(
    user_id=user_instance
).values('following_user_id')

posts = Posts.objects.filter(user__in=following_users)
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • Thank you that does it! Can you please explain why do you get `user_instance` the way you did instead of just `User.objects.get(id=num)` ? – euh Jul 06 '22 at 14:16
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 06 '22 at 19:26
  • 1
    By this way it will only return id of user instead of all data and also I think it is faster. – Samim Hamza Jul 07 '22 at 03:58