Split queryset into groups without multiple queries

How can I retrieve a ready-made queryset divided into two parts from a single model with just one database hit? For example, I need to fetch is_featured=True separately and is_featured=False separately.

I tried filter function of python but I want to do it alone with query itself is that possible.

I want to add 2 featured and 8 organic products on one page. In general, is it correct to divide them into two groups, bring them in, and then set the correct position for each?

p = Product.objects.all()
featured_products = filter(lambda p: p.is_featured, p)
list(featured_products)
[<Product: Nexia sotiladi | 2024-12-06 | -20241206>, <Product: Nexia sotiladi | 2024-12-06 | -20241206>` 
these are is_featured=True

that is what I did with python filter function

You can use itertools.groupby(…) [python-doc] to post-process the query:

from itertools import groupby
from operator import attrgetter

result = {
    k: list(vs)
    for k, v in groupby(
        Product.objects.order_by('is_featured'), attrgetter('groupby')
    )
}

This will make one query, and will generate a dictionary where the value of is_featured is mapped to a list of Product items.

I want to add 2 featured and 8 organic products on one page. In general, is it correct to divide them into two groups, bring them in, and then set the correct position for each?

For that you can use a .union(…) [Django-doc]:

Product.objects.filter(is_featured=True)[:2].union(
    Product.objects.filter(is_featured=False)[:8],
    all=True
)
Back to Top