Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Get object with the highest number of related objects

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!