Is Concatenating Django QuerySets In A Loop The Right Thing To Do?
-
11-09-2019 - |
Question
I have a Django model called Collection that represents a collection of items (CollectionItem). Each Collection only contains items of a specific type. (CollectionItem has a foreign key to Collection).
I want to get all of the CollectionItems that are in public-flagged lists of a specific type and return them sorted by a particular field. Here's the query code that I use:
lists = Collection.objects.filter(is_public=True, type=7)
items = CollectionItem.objects.none()
for list in lists:
items |= CollectionItem.objects.filter(collection=list)
items = items.order_by('name')
I have to imagine that this will not scale well at all when I have a large database with tons of lists and items. Is there a better way to do this in Django? Or is the inefficiency involved in the query loop negligible enough compared to other options that I shouldn't worry too much?
Solution
Sounds like you just need:
items = CollectionItem.objects.filter(
collection__is_public=True, collection__type=7
).order_by('name')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow