我想知道是否可以在模型上使用索引:
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
目前它抛出
“TypeError:'Buildings'对象是 unindexable“
我想做这样的事情的原因是使用索引会简化部分代码:
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
到此:
buildings[queue.kind_id] +=1
答案 0 :(得分:1)
get()
方法不返回查询集,只返回模型类的单个实例/对象。如果您想要检索多个对象(=查询集),请改用filter()
!
a=Buildings.objects.filter(...)
我不确定您是在尝试使用伐木工人,市政厅等属性... 我想你可以做点什么:
buildings_list = ['townhall', 'lumberjack', ....]
attr = buildings_list[queue.kind_id]
setattr(buildings, attr, getattr(buildings, attr) + 1)
但我不确定你要做什么,如果你正在使用django的模型,他们打算使用它们......