[Django]-Prefetch related starting from a single object – geting first in second prefetch and count and order

2👍

This query will get a little complicated, but should help you solve your issue.

PS: I haven’t tested this but should mostly work. Will take a deeper look once I get some more time.

First we get the company we want:

company = Company.objects.get(pk=company_pk)

Then we fetch all the first categories for all products, it can be done by using this question as a guide:

first_categories = Category.objects.order_by('product__id', '-id').distinct('product__id')

Now we use the first_categories to use to limit the amount of data we prefetch (giving this a different perspective, we will query the Product model instead of the Company model)

product_list = Products.objects.filter(company=company).prefetch_related(
    Prefetch('categories', queryset=first_categories)
)

def get_queryset():
    company_pk = ...
    company = ...
    first_categories = ...
    product_list = ...
    return product_list

Leave a comment