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

问题描述:

作为一个计算Django的项目,我正在尝试构建一个小游戏。Django模型:参考字段返回多种类型的模型

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

我有3个静态表,其中包含每个项目的第一级信息(在游戏中这些值用于公式计算升级东西)。我使用了一个序列将所有这些项目插入这些不同的表中,这样ID在各个表中都是唯一的。

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

警告:我关于Django模型的知识相当有限,而且我几天前一直坚持使用它。

这是可能的,如果是的话,该怎么办?

我尝试使用保存方法上的注释来改变字段的值,通过覆盖与该对象的id字段之前试图“获取”对象尝试通过id查询对象,但是我可以'吨得到过去的模式明显地限制定义该字段为整数时 - 我希望它不会验证,直到我打电话保存()

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 

如果我完全关闭,我能做到这一点不同,我所有的耳朵:)

我认为你正在寻找一个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) 

这可以让你创建的项目,如你所说,但是你可能需要看看过滤这些项目走出了一条不同的道路。

+0

这太好了。保存属性完美运行。唯一的缺点是我必须使用“building = Property.objects.all()。get(base = base,object_id = building.id)”而不是item = building,但它会工作得很好。谢谢! – Cornelis