【问题标题】:Django: how to filter a model with ManyToMany relationshipsDjango:如何过滤具有多对多关系的模型
【发布时间】: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


【解决方案1】:

试试这个:

Tag.objects.filter(product_set__isnull=False).values_list('nom', flat=True)

【讨论】:

  • 我尝试了相反的方法:Produit.tags.values_list('nom', flat=True),我得到了这个错误:'ReverseManyRelatedObjectsDescriptor' object has no attribute 'values_list'
【解决方案2】:

找到了!首先,通过像这样使用related_name 使ManyToMany 关系更具可读性:

class Produit(BaseModel):
    tags = models.ManyToManyField(Tag, related_name='produits')

然后,这就是我获取Produit 使用的所有Tag 的方法。我想它不是很优化,但它就像一个魅力:

class IndexView(generic.ListView):
    #blabbla ignoring code in-between
    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['produits_tags'] = list(
            Tag.objects.filter(produits__in=Produit.objects.all()).distinct()
        )
        context['produits_tags'].insert(0, _("All"))
        return context

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 2020-06-18
    • 2011-12-08
    • 2014-05-16
    • 1970-01-01
    • 2021-10-22
    • 2018-06-28
    • 2021-03-19
    相关资源
    最近更新 更多