Search code examples
pythondjangodjango-admininline-editing

Inline editing of ManyToMany relation in Django


After working through the Django tutorial I'm now trying to build a very simple invoicing application.

I want to add several Products to an Invoice, and to specify the quantity of each product in the Invoice form in the Django admin. Now I've to create a new Product object if I've got different quantites of the same Product.

Right now my models look like this (Company and Customer models left out):

class Product(models.Model):
    description = models.TextField()
    quantity = models.IntegerField()
    price = models.DecimalField(max_digits=10,decimal_places=2)
    tax = models.ForeignKey(Tax)

class Invoice(models.Model):
    company = models.ForeignKey(Company)
    customer = models.ForeignKey(Customer)
    products = models.ManyToManyField(Product)
    invoice_no = models.IntegerField()
    invoice_date = models.DateField(auto_now=True)
    due_date = models.DateField(default=datetime.date.today() + datetime.timedelta(days=14))

I guess the quantity should be left out of the Product model, but how can I make a field for it in the Invoice model?


Solution

  • You need to change your model structure a bit. As you recognise, the quantity doesn't belong on the Product model - it belongs on the relationship between Product and Invoice.

    To do this in Django, you can use a ManyToMany relationship with a through table:

    class Product(models.Model):
        ...
    
    class ProductQuantity(models.Model):
        product = models.ForeignKey('Product')
        invoice = models.ForeignKey('Invoice')
        quantity = models.IntegerField()
    
    class Invoice(models.Model):
        ...
        products = models.ManyToManyField(Product, through=ProductQuantity)