[Answer]-Django – Call model's method on demand to filter and prefetch data from a reversed foreignkey

1👍

Just filter the stores in python code:

for company in companies:
    open_stores = [s for s in company.store_set.all() if not s.closed]

Or manually prefetch the stores:

companies = Company.objects.filter(name__startswith="stackoverflow")

open_stores_d = {}
for store in Store.objects.filter(closed=False, company__in=companies):
    open_stores_d.setdefault(store.company, []).append(store)

for company in companies:
    open_stores = open_stores_d.get(company, [])

Leave a comment