[Answered ]-Intersection of QuerySet and list of objects

1๐Ÿ‘

โœ…

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.

Leave a comment