As a project to figure out Django I’m trying to build a small game.
A player has a base. A base has several type of items it can harbor. (Vehicle, Defense, Building).
I have 3 static tables which contain information for the first level of each item (in the game these values are used in formulas to calculate stuff for upgrades). I’ve used a sequence to insert all these items in these different tables so the ID’s are unique across tables.
To keep track of what items the player has per base I have a table ‘Property’. I want to use a single field as a reference to the ID of an item and trying to get this done with the Django models.
Warning: my knowledge about Django models are pretty limited and I’ve been stuck with this a few days now.
Is this possible and if so how can it be done?
I tried using annotations on the save method to change the value of a field by overwriting the field with the id of that object before trying to query the object by id when trying to ‘get’ the object, however I can’t get past the obvious restriction of the model when defining that field as an Integer – I hoped it wouldn’t validate until I called 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()
I hope you can help me here. The end result I’d like to be able to put to use would be something like:
# 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
If I’m completely off and I can achieve this differently I’m all ears 🙂
I think you are looking for a Generic Relationship:
This lets you create items as you mentioned, however you would probably need to look at a different way of filtering those items out.