【问题标题】:Django model field relating to a few modelsDjango模型字段涉及的几个模型
【发布时间】:2012-01-12 04:33:45
【问题描述】:

想象一个 5x5 的网格(地图),它的每个区域都代表一个特定的对象(可以是怪物、树等)

所以,我们有:

class Field(Model):
    x = y = PositiveIntegerField()
    content = ...(?)

问题来了。这是另一种选择,但我认为这种方式太乱了,尤其是如果我有许多不同的内容ID。

class Field(Model):
    x = y = PositiveIntegerField()
    content = PositiveIntegerField()

    monster_rel = ForeignKey(Monster, null=True, blank=True)
    building_rel = ForeignKey(Monster, null=True, blank=True)
    nature_obj_rel = ForeignKey(Monster, null=True, blank=True)

然后在视图中:

f = Field.objects.get(pk=1)
if f.content == 1:
    print "Monster %s of level %d" % (f.monster_rel.name, f.monster_rel.level)
elif f.content == 2:
    print "This is a %s" % f.building_rel.type
...

有没有更好的解决方案?

编辑 我想要这样的字段:

content_id = IntegerField()
content_rel = FieldRelatedToModelByContentId()

【问题讨论】:

    标签: django orm models


    【解决方案1】:

    嗯,听起来generic relations 正是您要找的。​​p>

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 2019-04-22
      • 2013-01-03
      • 1970-01-01
      • 2019-03-11
      • 2019-12-24
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多