这种多对多关系有意义吗?

Does this many-to-many relationship make sense?

我正在编写一个 Django 应用程序,下面有以下模型,但是我不确定 DetailedOrder 中的 order_id 和 product_id 以及 Demand 模型中的 customer_id 的关系.

在DetailedOrder 模型中,如果客户订购多个product_id,则可以有多个order_id (O0001)。然后可以在订单模型中使用 order_id 来查找客户是谁。

或者 DetailedOrder 中的 product_id 应该是多对多关系,因为 1 order_id 可以有多个产品 - 我认为这更有意义。

同样按照这个逻辑,Ordermodel中的customer_id是不是应该是多对多的关系,因为可以有多个customer_id到多个order_id?

如有任何建议,我们将不胜感激!

class Customer(models.Model):
    customer_id = models.CharField(primary_key=True, max_length=150)
    customer_name = models.CharField(max_length=150, null=True)

class Product(models.Model):
    product_id = models.CharField(primary_key=True, max_length=100)
    product_name = models.CharField(max_length=150)

class Order(models.Model):
    order_id = models.CharField(primary_key=True, max_length=100)
    customer_id = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)


class DetailedOrder(models.Model):
    order_id = models.ForeignKey(Demand, null=True, on_delete= models.SET_NULL)
    product_id = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
    quantity = models.IntegerField()

CSV 数据:

产品 csv:

product_id,product_name
P00001,TOOTHPASTE
P00002,SWEETS
P00003,CHOCOLATE
P00004,COMPUTER
P00005,LAPTOP
P00006,BRUSH
P00007,TOWEL

订单 csv:

order_id,customer_id

O00001,C00001
O00002,C00005
O00003,C00020
O00004,C00004
O00005,C00024

订单详情:

order_id,product_id,数量

O00001,P00001,5
O00001,P00004,9
O00001,P00003,7
O00002,P00005,2
O00002,P00006,7
O00002,P00002,7
O00003,P00004,6
O00003,P00006,7
O00004,P00004,8
O00004,P00011,1
O00004,P00002,2
O00005,P00003,4

您的 DetailOrder 充当 ManyToManyField 的直通模型。对于同一个 Order,您可以有多个 DetailedOrder,因此也可以引用多个 Product

您还可以跨越 ManyToManyField [Django-doc] over this model to effectively find out the Products, with DetailedOrder as the through=… model [Django-doc]:

class Product(models.Model):
    product_id = models.CharField(primary_key=True, max_length=100)
    product_name = models.CharField(max_length=150)

class Order(models.Model):
    order_id = models.CharField(primary_key=True, max_length=100)
    customer_id = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
    products = models.ManyToManyField(
        Product,
        <strong>through='DetailedOrder'</strong>,
        related_name='orders'
    )

class DetailedOrder(models.Model):
    order = models.ForeignKey(Order, null=True, on_delete= models.SET_NULL)
    product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
    quantity = models.IntegerField(default=1)

Note: Normally one does not add a suffix …_id to a ForeignKey field, since Django will automatically add a "twin" field with an …_id suffix. Therefore it should be product, instead of product_id.