Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM: filter by a list of objects

Tags:

orm

django

filter

I have the following code to put all my users from a multichoice field into a list

USERS = []
for user in User.objects.filter(groups__name='accountexec'):
    USERS.append((user.id,user))

I need to use Log.objects.filter() to get all the logs with a user= to a user in the USERS list

like image 264
Mike Avatar asked Jun 22 '09 18:06

Mike


People also ask

Does Django ORM support subquery?

¶ Django allows using SQL subqueries.

Can you filter a QuerySet?

Working with Filter Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters.

What is objects filter in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


1 Answers

Use the __in lookup:

Log.objects.filter(user__in=User.objects.filter(groups__name='accountexec'))
like image 69
Daniel Roseman Avatar answered Sep 18 '22 16:09

Daniel Roseman