Search code examples
djangopython-2.7webrelationshipmodels

understand models relationship . Its python, Django my q is ideologic


Im developing CRM system in which i have 2 models

Order


items_in_order=models.ManyToManyField(Item)

Item


name=models.Charfield()
price=models.DecimalField()

As you can see Orderlist can have multiple items in it.

I want to have order list in which i can add an items with quantity.

For example: ORDER

yellow flower (5$) | 10 pcs blue flower (3$) | 3pcs

For now i can only add these two flowers to order, without quantity. How these can be implemented ?


Solution

  • You can use the through model that you get while using ManyToMany fields

    class Order(models.Model):
        items_in_order=models.ManyToManyField('Item', through='Quantity')
    
    class Item(models.Mode):
        name=models.Charfield()
        price=models.DecimalField()
    
    class Quantity(models.Model):
        quantity = models.IntegerField()
        order = models.ForeignKey('Order')
        item = models.ForeignKey('Item')
    

    Documentation on extra fields on ManyToMany