django - Idiomatic way of counting number of related objects -
this how doing currently:
class article(models.model): ... def nr_notes(self): return len(note.objects.filter(article=self.pk)) class note(models.model): article = models.foreignkey(article, on_delete=models.cascade)
but thought "there must better way". accessing the generated notes_set
field?
what right way implement method nr_notes
?
yes, use count
, count query on database rather evaluating filter
note.objects.filter(article=self.pk).count()
from evaluating querysets:
a queryset evaluated when call len() on it. this, might expect, returns length of result list.
note: if need determine number of records in set (and don’t need actual objects), it’s more efficient handle count @ database level using sql’s select count(*). django provides count() method precisely reason.
Comments
Post a Comment