2011-11-02 152 views
2

作爲一個計算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 

如果我完全關閉,我能做到這一點不同,我所有的耳朵:)

回答

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) 

這可以讓你創建的項目,如你所說,但是你可能需要看看過濾這些項目走出了一條不同的道路。

+0

這太好了。保存屬性完美運行。唯一的缺點是我必須使用「building = Property.objects.all()。get(base = base,object_id = building.id)」而不是item = building,但它會工作得很好。謝謝! – Cornelis