Bastian
Bastian

Reputation: 5865

Django how to order by many to many occurences

let's say I have 2 models:

class Recipe(models.Model):
    recipe = models.TextField()
    ingredients = models.ManyToManyField(Ingredient)

class Ingredient(models.Model):
    name = models.CharField()

and I want to know what ingredient is the most used in all the recipes.

How do I query that?

Upvotes: 2

Views: 107

Answers (1)

Jordan Dimov
Jordan Dimov

Reputation: 1318

Read about aggregation and annotations at https://docs.djangoproject.com/en/dev/topics/db/aggregation/

To get the name of the most common ingredient:

from django.db.models import Count
most_common = Ingredient.objects.annotate(num_recipes=Count('recipe')).order_by('-num_recipes')[0]
print most_common.name

Upvotes: 2

Related Questions