【问题标题】:Django Many-to-Many data modelDjango 多对多数据模型
【发布时间】:2018-01-13 01:58:17
【问题描述】:

我正在尝试创建一个涉及产品、客户和订单的数据结构。客户和产品是独立的表,而订单引用产品和客户。

订单表字段:

  1. 时间戳
  2. 客户
  3. 产品和数量

这是我尝试创建一个 django 模型来实现这一点:

from django.db import models

class Customer(models.Model):
    name = models.CharField(max_length=30)
    latitude = models.FloatField(default=0)
    longitude = models.FloatField(default=0)

class Product(models.Model):
    name = models.CharField(max_length=30)
    weight = models.FloatField(default=0)

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now=True)
    products = models.ManyToManyField(Product)
    quantity = ?

如何创建映射到特定产品的数量字段?也欢迎使用其他模型来实现相同的结果。

【问题讨论】:

标签: python django django-models


【解决方案1】:

在您的 ManyToManyField 中使用 through

from django.db import models

class Customer(models.Model):
    name = models.CharField(max_length=30)
    latitude = models.FloatField(default=0)
    longitude = models.FloatField(default=0)

class Product(models.Model):
    name = models.CharField(max_length=30)
    weight = models.FloatField(default=0)

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now=True)
    line_items = models.ManyToManyField(Product, through='OrderItem')

class OrderItem(models.Model):
    product = models.ForeignKey(Product)
    order = models.ForeignKey(Order)
    quantity, price, discount, ...

【讨论】:

    【解决方案2】:

    我建议在订单中包含产品及其数量的模型。如下所示。

    class ProductOrder(models.Model):
        product = models.ForeignKey(Product)
        quantity = models.IntegerField()
    

    然后按顺序:

    class Order(models.Model):
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        timestamp = models.DateTimeField(auto_now=True)
        products = models.ManyToManyField(ProductOrder)
    

    【讨论】:

    • 谢谢,这是正确的方向。对我有用的是“通过=”
    猜你喜欢
    • 2019-02-09
    • 2016-07-17
    • 2019-09-15
    • 2023-04-06
    • 1970-01-01
    • 2014-09-17
    • 2011-12-20
    • 2019-05-09
    • 2020-05-04
    相关资源
    最近更新 更多