我有3个型号:
升级会跟踪正在升级的建筑物。
class Town(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=63)
class Building(models.Model):
template = models.ForeignKey(BuildingTemplate, related_name='building_template')
town = models.ForeignKey(Town)
level = models.IntegerField()
class Upgrade(models.Model):
building = models.ForeignKey(Building)
timer = models.DateTimeField()
现在我想计算一个城镇在升级时的建筑数量。现在我想我可以用一些for循环来做这个,但我想知道使用Django API是否有更好的方法。
答案 0 :(得分:1)
如果有多次升级,之前的答案将多次计算同一建筑物。请改用:
count = Building.objects.filter(town=town).exclude(upgrade=None).count()
答案 1 :(得分:0)
我发现链接文档对我有用:
count = Upgrade.objects.filter(building__town=building.town).count()