【问题标题】:Django: three models in relation to each other, what is the best wayDjango:三个模型相互关联,最好的方法是什么
【发布时间】:2013-04-06 08:36:43
【问题描述】:

我有一家网上商店。有单品要买,但也有一些套装包含其中一些单品。 现在我正在尝试为这些关系找到最佳/有用的解决方案。这就是我目前所拥有的。

型号:

class Wine(models.Model):
    name = models.CharField(max_length=128)

class WineBox(models.Model):
    name = models.CharField(max_length=128)
    wines = models.ManyToManyField(Wine)

class Product(models.Model):
    wine = models.OneToOneField(Wine, blank=True, null=True)
    winebox = models.OneToOneField(WineBox, blank=True, null=True)
    price = models.DecimalField(max_digits=4, decimal_places=2)
    public = models.BooleanField(blank=True)

【问题讨论】:

    标签: django many-to-many models relationship one-to-one


    【解决方案1】:

    感谢所有帮助,但最后我想出了一个非常简单的解决方案,完全符合我的需求。我不想使用泛型关系,因为我可以控制我的所有模型,它们使一切变得复杂,或者 Cartucho 解决方案,因为我以后可能想要更多的产品。我使用 Product 作为基类,现在模型看起来像:

    class Product(models.Model):
        price = models.DecimalField(max_digits=4, decimal_places=2)
        public = models.BooleanField(blank=True)
    
    class Wine(Product):
        name = models.CharField(max_length=128)
    
    class WineBox(Product):
        name = models.CharField(max_length=128)
        wines = models.ManyToManyField(Wine)
    

    【讨论】:

      【解决方案2】:

      WineBoxProduct 都需要吗?似乎有点多余。为什么不做一些更简单的事情,比如:

      class Wine(models.Model):
          name = models.CharField(max_length=128)
      
      class Product(models.Model):
          wine = models.ForeignKey(Wine)
          winebox = models.ManyToManyField(Wine)
          price = models.DecimalField(max_digits=4, decimal_places=2)
          public = models.BooleanField(blank=True)
      

      这看起来仍然是多余的,我宁愿从 Product 中删除 wine 字段并留下:

      class Product(models.Model):
          wines = models.ManyToManyField(Wine)
          price = models.DecimalField(max_digits=4, decimal_places=2)
          public = models.BooleanField(blank=True)
      

      希望对你有帮助。

      【讨论】:

      • 好点!我的第一个想法是向 WineBox 添加其他信息,例如包装照片或不同的标题。 (抱歉,我的问题没有那么具体。)但也许值得将其添加到 Product 类中,而不是添加一个额外的模型。
      • @horndash 我最好的建议是保持数据模型简单,不要过度设计。干杯!
      • 我会研究这个问题的通用关系:假设您想要拥有多种类型的产品,目前Product 只能将Wines 作为“内容”。看看这个:docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      相关资源
      最近更新 更多