[Answered ]-What is the best way to chain and filter DB queries in django?


Django Querysets are lazy so they don’t evaluate until you try to access the results. You can either chain the filters as your have done, or put them all in one. I guess it really depends on if you have all the information when you start or if you need to dynamically add the filters based on something. Either way, the end result of the query will be the same. Check out django’s documentation on the subject

friends_posts = Post.objects.filter(privacy=False, user=friends[0])

friends_posts = Post.objects.filter(privacy=False).filter(user=friends[0])

for your second part. I think you just want a simple ‘__in’ filter which will give you all the posts whose user is in the friends. (django’s docs)

friends_posts = Post.objects.filter(privacy=False, user__in=friends)

Django by default will let you have ‘friends’ be a queryset itself and will execute a subquery when it is getting the results. If you don’t want to execute a subquery, you can force your friends to a list and the it will query for the friends, then query for the posts.

friends_posts = Post.objects.filter(privacy=False, user__in=list(friends))


I think you may be looking for the ‘__in’ filter – ie:

def friend_posts(request):
    template = 'friends_page.html'

    friends = get_friends(request.user) # Gives you [user1, user2, user3] etc
    friend_posts = Post.objects.filter(privacy=False, author__in=friends)

    context = {'friend_posts': friend_posts}

    return render_to_response(template, context, RequestContext(request))

Leave a comment