Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query - join on the same table

Tags:

join

django

i have a mini blog app, and a 'timeline' . there i want to be displayed all the posts from all the friends of a user, plus the posts of that user himself. For that, i have to make some kind of a 'join' between the results of two queries (queries on the same table) , so that the final result will be the combination of the user - possessor of the account, and all his friends. My query looks like this:

blog = New.objects.filter(created_by = following,created_by = request.user)

By that ',' I wanted to make a 'join' - I found something like this on a doc- but this method is not correct - I'm getting an error.

How else could be done this 'join' ?

like image 452
dana Avatar asked Aug 18 '26 07:08

dana


1 Answers

You can use Django Q (query parameter) objects to create complex queries with logical operators (&, |, and ~). You can also use __ (double underscore) to join in query parameters.

# is this what you want?
blog = New.objects.filter( Q(created_by__followed_by = request.user)
                          |Q(created_by = request.user) )

For more details see http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects.

like image 170
George Steel Avatar answered Aug 23 '26 08:08

George Steel