【问题标题】:Properly assembling a drinks database with Django (Many to Many)使用 Django 正确组装饮料数据库(多对多)
【发布时间】:2019-10-16 23:07:50
【问题描述】:

我想建立一个饮料数据库,现在我遇到了数据库没有相应生成的问题,我不知道该怎么做。

我已经尝试了几件事,但不幸的是没有找到解决方案

数据库应该是什么样子:



Table 1 (Drinks)

-----------------------------------------------------------
drink_Id |  drink_name  | description | image_path | slug |
-----------------------------------------------------------

Table 2 (ingredients)
---------------------------------
ingredient_id | ingredient_name |
---------------------------------

Table 3 (drink_ratio)
---------------------
ID_ratio | quantity | 
---------------------

Table 4 ()
-----------------------------------------
id | drink_id | ingredient_id | ID_ratio |
-----------------------------------------

代码:




from django.db import models


class Drinks(models.Model):
    drink_name = models.CharField(max_length=256, unique=True)
    description = models.TextField()
    image_path = models.ImageField(upload_to="./images")
    slug = models.SlugField(unique=True)
    ingredient = models.ManyToManyField('ingredient')


    def __str__(self):
        return self.drink_name



class ingredient(models.Model):
    name = models.CharField(max_length=256, unique=True)

    liquid_ratio = models.ManyToManyField('liquid_ratio')


    def __str__(self):
        return self.name


class liquid_ratio(models.Model):
    quantity = models.DecimalField(max_digits=4, decimal_places=2, unique=True)

我想实现我只有 4 张桌子。 就像在顶部一样。

一种饮料可以有多种成分。 一种饮料只能存在一次。

一种饮料的每种成分只能有一个数量。

谢谢你:))

【问题讨论】:

    标签: python django database many-to-many


    【解决方案1】:

    我不确定您为什么需要单独的 drink_ratio 表。量是饮料和配料之间联系元素的一个属性,因此属于直通表(表4);表 3 根本不需要。您可以使用 through 参数在 Django 中对此进行建模:

    class Drink(models.Model):
        drink_name = models.CharField(max_length=256, unique=True)
        description = models.TextField()
        image_path = models.ImageField(upload_to="./images")
        slug = models.SlugField(unique=True)
        ingredient = models.ManyToManyField('Ingredient', through='IngredientRatio')
    
        def __str__(self):
            return self.drink_name   
    
    class Ingredient(models.Model):
        name = models.CharField(max_length=256, unique=True)
    
        def __str__(self):
            return self.name
    
    class IngredientRatio(models.Model):
        quantity = models.DecimalField(max_digits=4, decimal_places=2, unique=True)
        ingredient = models.ForeignKey('Ingredient', on_delete=models.CASCADE)
        drink = models.ForeignKey('Drink', on_delete=models.CASCADE)
    

    (注意,Django 模型应该以单数命名并使用 CamelCase。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 2016-02-01
      • 1970-01-01
      • 2015-12-31
      相关资源
      最近更新 更多