How to sort by presence of M2M (Pizza Example)

Say I have the common pizza example:

class Topping(models.Model):
    order = models.IntegerField()
    name = models.CharField(max_length=250)

class Pizza(models.Model):
    toppings = models.ManyToManyField(Topping)

With the following toppings:

Topping.objects.create(order=1, name="tomato")
Topping.objects.create(order=2, name="cheese")
Topping.objects.create(order=3, name="olives")
Topping.objects.create(order=4, name="salami")
Topping.objects.create(order=5, name="onion")
Topping.objects.create(order=6, name="rocket")

Now say I had a pizza with tomato, cheese and salami I wish to get an order list of all the toppings of the pizza according to the topping__order, along with a list of all the toppings it does not have, also ordered by topping__order So its sort by first where the pizza has the topping, and secondly by the topping__order field.

The result would be something that has the same info as this (probably in a queryset though):

    { "id": 1, "name": "tomato", "has_topping": True},
    { "id": 2, "name": "cheese", "has_topping": True},
    { "id": 3, "name": "salami", "has_topping": True},
    { "id": 2, "name": "olives", "has_topping": False},
    { "id": 5, "name": "onion" , "has_topping": False},
    { "id": 6, "name": "rocket", "has_topping": False},

Is this possible via a database query? (I can do it manually in python via two querries)

You can do it with .order_by() function:

Pizza.objects.all().order_by('id', 'toppings__order')
Back to Top