Home > database >  Django sequentially link tables through ForeignKey
Django sequentially link tables through ForeignKey

Time:07-07

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'

CodePudding user response:

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)
  • Related