Is it possible to get object which has the highest number of related objects?
I want to choose most used plan which is a plan with the maximal number of UserPlan objects.
I can get the number but not the instance.
number_of_users = Plan.objects.aggregate(max_users=Max('userplan'))['max_users']
code:
class UserPlan(Model):
plan = ForeignKey('Plan'..)
class Plan(Model):
...
@staticmethod
def favorite(self):
number_of_users = Plan.objects.aggregate(max_users=Max('userplan'))['max_users']
# ?
I could find it using loop but it could be slow.
Since the information is already stored in a column, how about we just sort it?
obj_most_popular = Plan.objects.order_by('userplan').first()
You can read more about it in the docs here: https://docs.djangoproject.com/en/1.10/ref/models/querysets/#order-by