Search code examples
djangodjango-modelsmodelmany-to-many

django shop app model definition


I am trying to make a shop app. I have the following models

class Item(models.Model):
    name = models.CharField(max_length=200)

class Order(models.Model):
    item = models.ManyToManyField(Item)

So what i want to achieve is add many items in one order but i would also want to specify the quantity of each item in the order but i cannot figure out a good way to do it. I thought of overriding save() after creating an order and create a custom form requesting a quantity for each item added. But maybe there is a better/easier way to achieve this?


Solution

  • Extra fields on many-to-many relationships

    When you’re only dealing with simple many-to-many relationships such as mixing and matching pizzas and toppings, a standard ManyToManyField is all you need. However, sometimes you may need to associate data with the relationship between two models.

    and

    For these situations, Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary. For our musician example, the code would look something like this:

    So we need another model. Shall we call it OrderItem?

    class OrderItem(models.Model):
        order = models.ForeignKey(Order)
        item = models.ForeignKey(Item)
        quantity = models.IntegerField()
    

    There after just change your many to many field to be

    item = models.ManyToManyField(Item,through='OrderItem')