4 ms·
users = User.objects.all() for u in user: print(u.name, len(u.comments)) This is fine if you are working with a small data set. It is inefficient,
by cuu508 5y ago
users = User.objects.all()
for u in user:
print(u.name, len(u.comments))
This is fine if you are working with a small data set. It is inefficient, but if it's quick enough, readability trumps efficiency IMHO.
Django ORM has a succinct way of doing the "SELECT COUNT(*)" pattern:
users = User.objects.all()
for u in user:
print(u.name, u.comments.count())
And you can use query annotations to get rid of the N+1 query issue altogether:
users = User.objects.annotate(n_comments=Count("comments"))
for u in user:
print(u.name, u.n_comments)
- tinus_hn 5y ago> This is fine if you are working with a small data set. It is inefficient, but if it's quick enough, readability trumps efficiency IMHO. And this is how you end up with the problems the parent is describing. During testing and when you setup the system you always have a small dataset so it appears to work fine. But when it’s real work the system collapses.