Reputation: 625
Imagine that:
I have "Posts", "Users", "UserFollowUser" models in a Django app...
I want to get all the POSTS from my POST model but only for people that I FOLLOW.
Every POST has a USER id of the user who is the author.
I mean, there's a register that says:
"Cris" follows "Larry"
I want to get the posts from Larry and some other people I follow.
I tried:
follows = UserFollowUser.objects.get(follower = request.user) #I AM request.user
posts = Post.objects.filter(user = follows.followed).order_by('-id')
But I can only get posts from ONE person because of the "GET" function in objects object.
Upvotes: 1
Views: 1238
Reputation: 81
This is code if you want to show posts of all users logged in user follows also your own posted posts in the feed:
follows_users = user.profile.follows.all()
follows_posts = Post.objects.filter(author_id__in=follows_users)
user_posts = Post.objects.filter(author=user)
post_list = (follows_posts|user_posts).distinct().order_by('-date_posted')
You can always take reference for social media django clone from https://github.com/uttampatel007/nccbuddy
Upvotes: 2
Reputation: 846
What you need to do is get an array of user ids for your followers. Then use the __in syntax to make a query where you are asking for all posts whose user id is in the set of user ids of your followers. The code would look something like this:
follower_user_ids = UserFollowUser.objects.filter(follower__user_id = request.user.id)\
.values_list('follower__user_id', flat=True)\
.distinct()
posts = Post.objects.filter(user_id__in=follower_user_ids)
*this assumes UserFollowUser.follower is a foreign key to the User table.
Upvotes: 6