【问题标题】:create django model with field names from list使用列表中的字段名称创建 django 模型
【发布时间】:2020-03-29 14:10:42
【问题描述】:

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

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

每个“玩家”在他的库存中有不同数量的水果。我会随着时间的推移改变可能的结果,因此我想从列表中动态创建这些字段。所以现在列表将是 ["apples", "bananas"],但在稍后的时间点我想要 ["apples", "oranges", "lemons"]。有没有办法从列表中创建字段名称?

【问题讨论】:

  • 不,没有。但这应该是一个不同的模型,Fruit,并且您应该使用多对多关系,可能使用“通过”关系来跟踪每个玩家的每个水果的数量。检查 django 文档中的多对多关系和“通过”关系。
  • 谢谢,我明白了

标签: django django-models


【解决方案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')

【讨论】:

    猜你喜欢
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2014-09-12
    相关资源
    最近更新 更多