tags:

views:

28

answers:

1

I was wondering if using indexes on a model was possible:

class Buildings(models.Model):
    island = models.ForeignKey(Island)
    townhall = models.IntegerField(default=1)
    lumberjack = models.IntegerField(default=0)
    stonequarry = models.IntegerField(default=0)
    ironmine = models.IntegerField(default=0)
    [...]

a=Buildings.objects.get(somecondition)
print a.townhall # 1
a[1] +=1
print a.townhall # 2

Currently it throws

"TypeError: 'Buildings' object is unindexable"

The reason why I'd like to do something like this is that using indexes would simplify parts of code like this:

if queue.kind_id == 0: buildings.townhall += 1
elif queue.kind_id == 1: buildings.lumberjack += 1
elif queue.kind_id == 2: buildings.stonequarry += 1
elif queue.kind_id == 3: buildings.ironmine += 1
elif queue.kind_id == 4: buildings.factory += 1
elif queue.kind_id == 5: buildings.shipyard += 1
elif queue.kind_id == 6: buildings.university += 1

to this:

buildings[queue.kind_id] +=1
+1  A: 

The get() method doesn't return a queryset, only a single instance/object of the model class. If you want want to retrieve more than one object (=a queryset) use filter() instead!

a=Buildings.objects.filter(...)

I am not sure what you are trying to use the lumberjack, townhall etc attributes for... I think you could do something like:

buildings_list = ['townhall', 'lumberjack', ....]
attr = buildings_list[queue.kind_id]
setattr(buildings, attr, getattr(buildings, attr) + 1)

But I am not sure what you are trying to do and if you are using django's models in the way they are inteded to be used...

lazerscience
Uh my mistake :P I meant referencing the values in a single object via indexes. as to make object[0] reference object.townhall, object[1] -> object.lumberjack ETC
Robus