django 商店应用程序模型定义
django shop app model definition
我正在尝试制作一个商店应用程序。
我有以下型号
class Item(models.Model):
name = models.CharField(max_length=200)
class Order(models.Model):
item = models.ManyToManyField(Item)
所以我想要实现的是在一个订单中添加许多项目,但我也想指定订单中每个项目的数量,但我想不出一个好的方法来做到这一点。我想在创建订单后覆盖 save()
并创建一个自定义表单,请求添加的每个项目的数量。但也许有 better/easier 方法可以实现这一点?
Extra fields on many-to-many relationships
When you’re only dealing with simple many-to-many relationships such
as mixing and matching pizzas and toppings, a standard ManyToManyField
is all you need. However, sometimes you may need to associate data
with the relationship between two models.
和
For these situations, Django allows you to specify the model that will
be used to govern the many-to-many relationship. You can then put
extra fields on the intermediate model. The intermediate model is
associated with the ManyToManyField using the through argument to
point to the model that will act as an intermediary. For our musician
example, the code would look something like this:
所以我们需要另一个模型。我们可以称它为 OrderItem
吗?
class OrderItem(models.Model):
order = models.ForeignKey(Order)
item = models.ForeignKey(Item)
quantity = models.IntegerField()
之后只需将您的多对多字段更改为
item = models.ManyToManyField(Item,through='OrderItem')
我正在尝试制作一个商店应用程序。 我有以下型号
class Item(models.Model):
name = models.CharField(max_length=200)
class Order(models.Model):
item = models.ManyToManyField(Item)
所以我想要实现的是在一个订单中添加许多项目,但我也想指定订单中每个项目的数量,但我想不出一个好的方法来做到这一点。我想在创建订单后覆盖 save()
并创建一个自定义表单,请求添加的每个项目的数量。但也许有 better/easier 方法可以实现这一点?
Extra fields on many-to-many relationships
When you’re only dealing with simple many-to-many relationships such as mixing and matching pizzas and toppings, a standard ManyToManyField is all you need. However, sometimes you may need to associate data with the relationship between two models.
和
For these situations, Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary. For our musician example, the code would look something like this:
所以我们需要另一个模型。我们可以称它为 OrderItem
吗?
class OrderItem(models.Model):
order = models.ForeignKey(Order)
item = models.ForeignKey(Item)
quantity = models.IntegerField()
之后只需将您的多对多字段更改为
item = models.ManyToManyField(Item,through='OrderItem')