我有一种情况需要在这些产品上存储“产品”表和“订单”表。
一个订单包含许多(“产品”,“数量”)元组,其中数量是以吨表示的浮点数。
我考虑过后续实施,但我不认为拥有任意产品和数量表是一个非常好的设计决策。
class Product(models.Model):
name = models.CharField("Name", max_length=50)
description = models.TextField("Description", blank=True)
class ProductOrder(models.Model):
unit = "tonnes"
product = models.ManyToManyField('Product')
quantity = models.FloatField('Quantity')
class Order(models.Model):
products = models.ManyToManyField('ProductOrder')
date = models.DateField('Date')
我是否忽视了一个明显的解决方案?您将如何实现此关系以获得最干的代码。 (PS。我不想单独列出产品和数量,并且必须隐含地依赖他们的订购。)
答案 0 :(得分:2)
在django中,您可以使用through
创建此类中间表并在其中维护特定于订单的属性。
您可以将其实现为
class Product(models.Model):
name = models.CharField("Name", max_length=50)
description = models.TextField("Description", blank=True)
class Order(models.Model):
products = models.ManyToManyField('Product', through="OrderDetail")
date = models.DateField('Date')
class OrderDetail(models.Model):
unit = "tonnes"
product = models.ForeignKey('Product')
order = models.ForeignKey('Order')
quantity = models.FloatField('Quantity')
该文档说明了如何使用和使用此类设计。