我有三种型号:
class Target(models.Model):
fqdn = models.CharField(max_length=100)
ports = models.ManyToManyField('Port')
class Port(models.Model):
status = models.CharField(max_length=20)
services = models.ManyToManyField('Service')
class Service(models.Model):
name = models.CharField(max_length=200)
vuls = models.ManyToManyField('Vul')
class Vul(models.Model):
code = models.CharField(max_length=100)
name = models.CharField(max_length=200)
和一个模板,我要在其中计算特定目标的目标:
{% for t in targets %}
Target: {{ t.fqdn }}
Count Vuls: {{ t.ports.services.vuls.count }}
{% endfor %}
如果我计算端口:
t.ports.count
没有问题... 但是,如何计算“超过”多个关系呢?
答案 0 :(得分:0)
我认为有一个“解决方案” ...
class Target(models.Model):
fqdn = models.CharField(max_length=100)
ports = models.ManyToManyField('Port')
#counts vuls for every target
def getSumVuls(self):
sum = 0
for p in ports.all():
for s in p.services.all():
sum = sum + s.vuls.count()
return sum
class Port(models.Model):
status = models.CharField(max_length=20)
services = models.ManyToManyField('Service')
class Service(models.Model):
name = models.CharField(max_length=200)
vuls = models.ManyToManyField('Vul')
class Vul(models.Model):
code = models.CharField(max_length=100)
name = models.CharField(max_length=200)
在模板中,我将调用getSumVuls()方法:
{% for t in targets %}
Target: {{ t.fqdn }}
Count Vuls: {{ t.getSumVuls }}
{% endfor %}
我对这种“解决方案”并不满意……我认为性能是一个问题!?!?