Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
Django Query, find most common value for field on a many to many relation

Given these models (where a Restaurant has many Pizzas and Pizzas have many Toppings)

class Restraunt(Model)

class Topping(Model):
  name = Charfield()

class Pizza(Model):
  in_resteraunt = ForeignKey(Resteraunt) 
  toppings = ManyToMany(topping, related_name='on_pizza')

I'm trying to figure out how: Given a Restaurant, across all its Pizzas, what is the most common topping?

One thing I came up with is something like this (where R = the restaurant)

Topping.objects.filter(on_pizza__restaurant=R).annotate(the_count=Count('on_pizza')).order_by('-the_count')[0]

The problem here is that I'm not sure if the on_pizza is unique to the Restaurant object, basically a topping object can be on a pizza at multiple restaurants I need it to be unique. Here I'm starting from the Topping, is there a way I could start from a queryset of pizzas?

I've looked into subquery expressions but don't really see how to implement

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The problem here is that I'm not sure if the on_pizza is unique to the Restaurant object, basically a topping object can be on a pizza at multiple restaurants I need it to be unique.

The query is correct. You filter on the restaurant, so that means that in the Count, it will only count Pizzas that are for the restaurant R. So this will indeed calculate the most common topping for pizzas made in restaurant R.

The query will thus look like:

SELECT topping.*, COUNT(pizza.pk)
FROM topping
LEFT OUTER JOIN pizza_toppings ON pizza_toppings.topping_id = topping.id
LEFT OUTER JOIN pizza ON pizza.id = pizza_toppings.pizza_id
WHERE pizza.restaurant_id = id_of_r
GROUP BY topping.pk
ORDER BY COUNT(pizza.pk)
LIMIT 1
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda