【发布时间】:2015-10-21 20:08:08
【问题描述】:
我有一个通用的 ListView,我可以在其中得到一些通用的东西(它与我的问题无关)。
我的模型Product 与Tag 具有ManyToMany 关系,即Product 可以有很多Tag,而Tag 可以链接到很多Product。
在这个通用 ListView 中,我想过滤所有实际上具有 Product 的 Tag,以便客户可以点击 Tag,然后我可以稍后进行过滤。
到目前为止,我想到了这个:
class IndexView(generic.ListView):
template_name = 'produits/index.html'
context_object_name = 'liste_produits'
def get_queryset(self):
"""Return the last five created products."""
return Produit.objects.order_by('-date_v_fin', '-date_v_debut')[:5]
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['produits_tags'] = list(
Tag.objects.values_list('nom', flat=True)
)
context['produits_tags'].insert(0, _("Tous"))
return context
但是Tag.objects.values_list('nom', flat=True)返回所有Tag,包括那些没有Product的。如何过滤?
【问题讨论】:
-
我不太清楚你在追求什么。您只想显示包含产品的所有标签,还是要遍历产品并显示每个产品的标签?
-
@DanielRoseman 我想显示所有包含产品的标签
标签: django django-models models