Eric Palakovich Carr
Eric Palakovich Carr

Reputation: 23338

Sorting ManyToMany field automatically in Django model

I currently have a set of models that look similar to this contrived code:

class Pizza(models.Model):
    price = models.FloatField()
    topping = models.ManyToManyField(Topping, through="PizzaToppings")

class Topping(models.Model):
    name = models.CharField(max_length=50)

class PizzaToppings(models.Model):
    class Meta:
        ordering=["order_to_add_topping"]

    pizza = models.ForeignKey(Pizza)
    topping = models.ForeignKey(Topping)
    order_to_add_topping = models.IntegerField()

My problem is that what happens when I attempt to access the toppings of a pizza in the order specified in the PizzaToppings ManyToMany extra fields table. Assume the pizza has cheese and ham, with the order_to_add_topping in the PizzaToppings data set to 0 and 1 respectively:

>>> pizza = Pizza.objects.get(pk=490)
>>> pizza.toppings.all()[0].name
'Ham'

That should say 'Cheese'. I would have thought the RelationManager would have respected the ordering Meta class field, but it appears it doesn't. So I guess accessing the name of the first topping added to the pizza shouldn't be done with pizza.toppings.all()[0].name.

How should it be accessed? Is the problem with my model query or is it how I have my models set up?

Upvotes: 1

Views: 3069

Answers (1)

cy lee
cy lee

Reputation: 86

Your model is fine you just need to query the relationship since now you have a "through" relationship with extra fields. The relationship is created automatically as topping_relationship in your case, so your query should be:

pizza.toppings.order_by('topping_relationship__order_to_add_topping')

Upvotes: 7

Related Questions