Django模型:参考字段返回多种类型的模型

时间:2011-11-02 21:40:39

标签: django models

作为一个弄清楚Django的项目,我正在尝试构建一个小游戏。

玩家有基础。基地有几种类型的物品可以藏。 (车辆,国防,建筑)。

我有3个静态表,其中包含每个项目第一级的信息(在游戏中,这些值用于公式计算升级的内容)。我已经使用序列在这些不同的表中插入所有这些项目,因此ID在表格中是唯一的。

为了跟踪玩家每个基地的物品,我有一个表'物业'。我想使用单个字段作为对项目ID的引用,并尝试使用Django模型完成此操作。

警告:我对Django模型的了解非常有限,几天后我一直坚持这一点。

这可能吗?如果可以的话怎么办呢?

我尝试在save方法上使用注释来更改字段的值,方法是在尝试“获取”对象时尝试通过id查询对象,然后用该对象的id覆盖字段,但是我不能在将该字段定义为整数时,超越模型的明显限制 - 我希望它在我调用save()之前不会验证

def getPropertyItemID(func):
    """
    This method sets the referral ID to an item to the actual ID.
    """

    def decoratedFunction(*args):
        # Grab a reference to the data object we want to update.
        data_object=args[0]

        # Set the ID if item is not empty.
        if data_object.item is not None:
            data_object.item=data_object.item.id

        # Execute the function we're decorating
        return func(*args)

    return decoratedFunction

class Property(models.Model):
    """
    This class represents items that a user has per base.
    """

    user=models.ForeignKey(User)
    base=models.ForeignKey(Base)
    item=models.IntegerField()
    amount=models.IntegerField(default=0)
    level=models.SmallIntegerField(default=0)

    class Meta:
        db_table='property'

    @getPropertyItemID
    def save(self):
        # Now actually save the object
        super(Property, self).save()

我希望你能在这里帮助我。我希望能够使用的最终结果是:

    # Adding - automatically saving the ID of item regardless of the class 
    # of item
    item = Property(user=user, base=base, item=building)
    item.save()

    # Retrieving - automatically create an instance of an object based on the ID 
    # of item, regardless of the table this ID is found in.
    building = Property.objects.all().distinct(True).get(base=base, item=Building.objects.all().distinct(True).get(name='Tower'))
    # At this point building should be an instance of the Building model

如果我完全离开了,我可以做到这一点,我全都听见了。)

1 个答案:

答案 0 :(得分:3)

我认为您正在寻找Generic Relationship

class Property(models.Model):
    user=models.ForeignKey(User)
    base=models.ForeignKey(Base)
    content_type = models.ForeignKey(ContentType) # Which model is `item` representing?
    object_id = models.PositiveIntegerField() # What is its primary key?
    item=generic.GenericForeignKey('content_type', 'object_id') # Easy way to access it.
    amount=models.IntegerField(default=0)
    level=models.SmallIntegerField(default=0)

这可以让你按照提到的方式创建项目,但是你可能需要查看一种不同的方法来过滤这些项目。

相关问题