Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I want to make a 'timeline' containing all mini blog posts from a user, and all the user he is following.
I want all these posts to be ordered by date., but how can I 'join' the posts, because the 'following' relation is in another table, so I have to make some kind of a join between the two tables, for taking the data.
For now, in my 'timeline', there appears only the blog posts of the owner of the blog, and I user a query like:
blog = New.objects.filter(created_by = request.user)
but I want to join there posts with the posts of the persons he is following, meaning:
following = Relations.objects.filter(initiated_by = request.user)
where Relations is the 'Follow relation' table.
How can I do it?
My models:
class New(models.Model):
post = models.CharField(max_length=120)
date = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, blank=True)
objects = NewManager()
class Relations(models.Model):
initiated_by = models.ForeignKey(User, editable=False, related_name = 'initiator')
date_initiated = models.DateTimeField(auto_now=True, editable = False)
follow = models.ForeignKey(User, editable = False, related_name = "follow")
date_follow = models.DateTimeField(auto_now=True, editable = False)
Maybe something like (using Q objects):
blogs = New.objects.filter(Q(created_by = request.user) | Q(relations_set__initiated_by = request.user))
This assumes that you have a foreign key from Relations
to New
. See the documentation about following relationships backward.
If your Relations
model doesn't have a foreign key to New
but a foreign key to the users table, say following = models.ForeignKey(User)
, then you can maybe do something like
blogs = New.objects.filter(Q(created_by = request.user) | Q(created_by__follow__initiated_by = request.user))
Now, your foreign key from the Relations
model to the user model should have related_name = 'follow'
.
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.