Inline editing of ManyToMany relation in Django

后端 未结 1 1182
时光取名叫无心
时光取名叫无心 2021-02-10 17:07

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

1条回答
  •  一生所求
    2021-02-10 17:42

    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)
    

    0 讨论(0)
提交回复
热议问题