Inline editing of ManyToMany relation in Django

两盒软妹~` 提交于 2019-12-04 14:35:59

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/1714995/inline-editing-of-manytomany-relation-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!