0

我试图在 Django 中表示一种混合物。就像是:

Chemical #1 - 50%
Chemical #2 - 30%
Chemical #3 - 20%

我想我会使用一个名为 composition 的包装器,如下所示:

class Composition(models.Model):
    """ Just a Wrapper """
    def save(...):
        #Validate ingredients add up to 100% and such


class Ingredient(models.Model):
    composition = models.ForeignKey('Composition',related_name='ingredients')
    name = models.CharField(max_length = 10)
    percentage = models.IntegerField()

我很确定有更好的方法来做到这一点。请记住,我这样做是为了以后可以在 Django 管理员中使用内联。大家有什么推荐的?非常感谢 =)

4

1 回答 1

3

在我看来,最好保留一份成分列表,然后在创建作品时参考这些成分,而不是每次都输入成分名称。您可以使用多对多关系和直通表来做到这一点,如下所示:

class Ingredient(models.Model):
    name = models.CharField(max_length=10)

class Composition(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient, through='CompositionIngredient')

    def save(...):
        #Validate ingredients add up to 100% and such

class CompositionIngredient(models.Model):
    composition = models.ForeignKey(Composition)
    ingredient = models.ForeignKey(Ingredient)
    proportion = models.DecimalField()

有关更多信息,请参阅Django 文档

编辑:这是有关如何通过管理界面中的表格进行处理的文档。

于 2011-11-22T23:15:27.937 回答