1👍
✅
You can .annotate(…)
[Django-doc] with:
from django.db.models import Count
User.objects.annotate(num_posts=Count('post'))
The User
objects that arise from this QuerySet
will have an extra attribute .num_posts
.
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Source:stackexchange.com