Reputation: 77
I'm currently working on a project where there is twitter-style one way following, and I've been unable to figure out how to select 'posts' in the database based on who the user is following.
I'm using the default user functionality, and then this is my following model:
class Following(models.Model):
user = models.ForeignKey(User, related_name="user")
following = models.ForeignKey(User, related_name="following")
and my posts model:
class Post(models.Model):
title = models.CharField(max_length=100)
text = models.TextField()
user = models.ForeignKey(User)
date_time = models.DateTimeField(auto_now=True)
Finally, the snippet from my view that I'm trying to get to work:
def home(request):
following = Following.objects.filter(user=request.user)
posts = Post.objects.filter(/*not sure what to put here*/)
I've been trying all night to get this working and I can't really see a solution, so any help would be awesome.
if there's anything that you might need to look at that I haven't posted here, the github repository for this project is here
Upvotes: 1
Views: 482
Reputation: 31524
My django is getting rusty, but here goes:
posts = Post.objects.filter(user__following__user=request.user)
Upvotes: 3
Reputation:
from django.db import transaction
@transaction.commit_manually
def get_posts(following):
posts = []
for f in following:
posts.append(Post.objects.filter(user=f))
transaction.commit()
return posts
def home(request):
following = Following.objects.filter(user=request.user)
posts = get_posts(following)
Upvotes: 0