python - Django 中 ManyToMany 关系的内联编辑

标签 python django django-admin inline-editing

完成 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/

相关文章:

Python 脚本策略 : running script twice vs excec

python - 为什么两个变量的值在 Python 中都会发生变化?

python - block 中的 Django 模板翻译是不可能的

python - Django 管理操作添加批量多字段?

python - 如何解决 Google calendar API 中的 Http Error 403 "Insufficient Permission"?

python - Pymc3 python函数确定性

python - 如何通过 mod-wsgi 使用 FCKEditor 的图像上传和浏览器?

python - Tastypie 如何将模型中的错误正确地反馈给用户?

django - 根据数据库中的值在Django Admin中隐藏模型

python - 在 django admin 中显示 m2m_changed 信号的验证错误