作为一个了解 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
如果我完全关闭并且我可以以不同的方式实现这一点,我会洗耳恭听:)
最佳答案
我认为您正在寻找 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)
这可以让您按照您提到的方式创建项目,但是您可能需要采用不同的方式来过滤这些项目。
关于Django 模型 : Reference field return multiple type of models,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7987655/