python - Django queryset efficiency -
i have item
object has foreignkey receipt
object.
class receipt(models.model): ... class item(models.model): receipt = models.foreignkey(receipt) name = models.charfield(max_length=255) cost = models.decimalfield(default=0, max_digits=6, decimal_places=3) ...
i display receipts using generic view.
class receiptview(detailview): model = receipt
and on template, want show items on receipt.
<ul> {% item in object.item_set.all %} <li>{{ item.name }}</li> {% endfor %} </ul>
this works fine smaller data sets. 1 of receipt objects has 1600 items related it. loading page receipt incredibly slow. using django debug toolbar notice django executing 1 query per item.
if alter list item in template rather displaying property of item, display item itself, django executes single query.
<ul> {% item in object.item_set.all %} <li>{{ item }}</li> {% endfor %} </ul>
unfortunately need display 10 of item's properties in template. there someway can tell django execute single query items , of properties?
use prefetch_related
. since doing reverse foreign key lookup, you're working manytomany relationship. prefetch_related
separate query under hood, retrieve , cache of receipt
objects you.
since you're using generic views, rather specifying model
, can specify queryset
.
class receiptview(detailview): queryset = receipt.objects.prefetch_related('related_items')
in order this, you'll have specify related_name
in item
model:
class item(models.model): receipt = models.foreignkey(receipt, related_name='related_items')
Comments
Post a Comment