在 Django 中建模产品订单

Modeling product orders in Django

我有一个特定产品列表的订单,我需要在 Django 中对其进行建模。

每个订单都有属性:

id
email
total_price
line_items

line_items 是产品字典和该产品所需的实例数。

产品是描述 class 产品的单独模型。

我需要 Product 和 Order 之间的多对多关系,因为每个产品可能是多个订单的一部分,但每个订单可能有很多产品 - 如果我有一个订单,这在我的字段中看起来如何有一个产品的 3 个实例,另一个产品的 2 个实例......?

line_items is a dictionary of products and the number of instances of that product required.

我建议不要将其存储在字典中。在关系数据库中,通常将其存储在多个记录的不同 table 中。这样做的好处,就是方便查询。例如生成包含某个产品的所有订单的列表,或者包含某个产品的数量大于 50.

因此我们通常有三个 table:

+-------+  1    N  +--------------+  N    1  +---------+
| Order |----------| OrderProduct |----------| Product |
+-------+          +--------------+          +---------+
| email |          | quantity     |
+-------+          +--------------+

这样我们就有了三个模型:OrderOrderProductProduct,例如:

Order(models.Model):
    email = models.EmailField()

Product(models.Model):
    # ...
    pass

OrderProduct(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    class Meta:
        unique_together = ('order', 'product')

因此我们可以构建一个订单:

product1 = Product.objects.create()
product2 = Product.objects.create()
my_order = Order.objects.create(email='foo@bar.com')
OrderProduct.objects.create(product=product1, order=my_order)
OrderProduct.objects.create(product=product2, order=my_order, quantity=14)

所以这里我们构建了两个产品和一个订单,我们在这个订单中添加了两个OrderProduct,一个用于product1,一个用于product2,数量为14.