完成 Django 教程后,我现在正在尝试构建一个非常简单的发票应用程序。
我想将多个产品添加到发票中,并在 Django 管理的发票表单中指定每个产品的数量。现在,如果我有不同数量的同一产品,我必须创建一个新的产品对象。
现在我的模型看起来像这样(公司和客户模型被遗漏了):
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))
我想数量应该被排除在产品模型之外,但我怎样才能在发票模型中为它创建一个字段?
最佳答案
您需要稍微更改一下模型结构。如您所知,数量不属于产品模型 - 它属于产品和发票之间的关系。
要在 Django 中执行此操作,您可以使用 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)
关于python - Django 中 ManyToMany 关系的内联编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1714995/