我正在开发Django web应用程序,并有以下查询:
我有一个名为“AppQoSList”的模型,它列出了所有用户可以使用的应用程序。
然后,我有了另一个名为'BasicAppSDWANProfiles‘的模型,它与'AppQoSList’有一个ManyToMany关系。
简而言之,这意味着用户可以拥有多个与他的帐户相关联的“BasicAppSDWANProfiles”,多个AppQoS可以位于特定的BasicAppSDWANProfiles中:
class AppQoSList(models.Model):
app_qos_name = models.CharField(max_length=50, blank=None, null=True)
app_qos_description = models.CharField(max_length=500)
def __str__(self):
return u'%s' % self.app_qos_name
class BasicAppSDWANProfiles(models.Model):
profile_name = models.CharField(max_length=30)
profile_basic_app_qos = models.ManyToManyField(AppQoSList)
tenant_id = models.ForeignKey(Tenant, default=3)当我试图显示可用的应用程序列表和相关的BasicAppSDWANProfile时,我面临模板中的问题:
{% for app in apps %}
{% for profile_app in sdwan_prof %}
{% for specific_app in profile_app.profile_basic_app_qos.all %}
{% ifchanged specific_app.pk %}
{% if app.pk == specific_app.pk %}
<td><h4><span class="label label-primary">{{ profile_app.profile_name }}</span></h4></td>
{% else %}
<td><h4><span class="label label-warning">Not Assigned</span></h4></td>
{% endif %}
{% endifchanged %}
{% endfor %}
{% endfor %}
{% endfor %}此代码的问题是在每一行上显示6次“未分配”(对应于在与此用户关联的BasicAppSDWANProfiles中找到的应用程序的数量),而我只想显示一次:

你有什么解决办法吗?
提前谢谢。
发布于 2017-09-08 10:39:40
我能够解决这个问题。
首先,我确实清理了视图代码,以删除重复的“未赋值”值。
我向模板上下文传递一本字典,其中只有指定了配置文件的应用程序,如下所示:
{'citrix-static': 'DPS-BLACKLIST',
'exchange': 'DPS-BLACKLIST',
'ms-lync-audio': 'DPS-WHITELIST',
'ms-update': 'DPS-GREYLIST',
'rtp': 'DPS-WHITELIST',
'share-point': 'DPS-WHITELIST'}在我的模板中,我只循环遍历这个字典:
{% for k,v in app_prof_assign.items %}
{% if app.app_qos_name == k %}
<td><h4><span class="label label-primary">{{ v }}</span></h4></td>
{% endif %}
{% endfor %}然后,我只需检查应用程序是否在profile字典中,在循环之外:
{% if app.app_qos_name not in app_prof_assign %}
<td><h4><span class="label label-warning">Not Assigned</span></h4></td>
{% endif %}最后,我可以像预期的那样填充表:

https://stackoverflow.com/questions/46088127
复制相似问题