Search code examples
djangodjango-orm

Intersection of QuerySet and list of objects


Assume that I have a query set of Product model.

products_qs = Product.objects.filter(...)
products_list = [<Product 1>, <Product 5>]

How can I detect intersection of products_qs and products_list?


Solution

  • If the Products in the product_list have a primary key, you can filter with:

    products_qs.filter(pk__in=[product.pk for product in product_list])

    This will do the filtering at the database side. If the queryset is not loaded into memory, this will be more efficient, since you will only retrieve Products from the database that are in the intersection.

    That being said, a list of model objects typically means there is something wrong with the code, only in certain cases, for example preparing a list of objects to be created or updated, using a list makes sense. A QuerySet has the advantage that there is an API to further filter the collection down, order it, etc. and is lazy, hence it does not load the items eagerly.