Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda