问题描述
在完成Django教程之后,我正在尝试构建一个非常简单的发票应用程序。
After working through the Django tutorial I'm now trying to build a very simple invoicing application.
我想将几个产品添加到发票中,并指定Django管理员中发票表单中的每个产品的数量。现在我必须创建一个新的Product对象,如果我有同一个产品的不同量子。
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.
现在我的模型看起来像这样(公司和客户的模型离开out):
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))
我猜数量应该不在产品型号的范围内,但是如何在发票模型中为其创建一个字段? / p>
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?
推荐答案
你需要改变你的模型结构。您知道,数量不属于产品型号 - 它属于产品和发票之间的关系。
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.
要在Django中执行此操作,您可以使用的ManyToMany关系:
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)
这篇关于在Django中进行ManyToMany关系的内联编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!