使用列表中的字段名称创建Django模型

时间:2020-03-29 14:10:42

标签: django django-models

在我的models.py文件中有一个Django模型,如下所示:

class Inventory(models.Model):
    player = models.CharField(max_length=30)
    apples = models.IntegerField()
    bananas = models.IntegerField()

每个“玩家”的库存中有不同数量的水果。随着时间的推移,我将更改可能的结果,因此,我想从列表中动态创建这些字段。因此,现在的列表将是[“ apples”,“ bananas”],但是稍后我希望使用[“ apples”,“ oranges”,“ lemons”]。有没有一种方法可以从列表中创建字段名称?

1 个答案:

答案 0 :(得分:1)

您可能想要查看models.ManyToManyField,并使用一个“虽然”关系。 https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/ https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ManyToManyField.through

class Fruit(models.Model):
    name = models.CharField(max_length=30)

class Inventory(models.Model):
    player = models.CharField(max_length=30)
    fruits = models.ManyToManyField(
        Fruit,
        through='FruitContent'
    )

class FruitContent(models.Model):
    fruit = models.ForeignKey(Fruit, models.CASCADE)
    inventory = models.ForeignKey(Inventory, models.CASCADE)
    count = models.PositiveIntegerField()

    # Protect your data structure
    class Meta:
        constraints = [
            UniqueConstraint(fields=['fruit', 'inventory'], name='unique_ownership')
        ]

这与保留库存模型有关,但这确实有点尴尬。我更喜欢这样的东西:

class Fruit(models.Model):
    name = models.CharField(max_length=30)

class Player(models.Model):
    name = models.CharField(max_length=30)
    inventory = models.ManyToManyField(
        Fruit,
        through='PlayerFruits'
    )

class PlayerFruits(models.Model):
    fruit = models.ForeignKey(Fruit, models.CASCADE)
    player = models.ForeignKey(Player, models.CASCADE)
    count = models.PositiveIntegerField()

    # Protect your data structure
    class Meta:
        constraints = [
            UniqueConstraint(fields=['fruit', 'player'], name='unique_ownership')