【问题标题】:Filter product_set in django-mptt在 django-mptt 中过滤 product_set
【发布时间】:2018-01-09 07:19:17
【问题描述】:

有 2 个模型

class Category(MPTTModel):
    title = models.CharField()
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

class Product(models.Model):
    category = models.ForeignKey(Category, blank=True, null=True)

我想从两个模型中获取树。 现在我可以得到:

在视图中

nodes = Category.objects.all()

在模板中

{% for n in nodes %}
  {% for t in n.product_set.all %}

但我想得到

nodes = Category.objects.all().**insert_to_category_product_with_filter**(id__in=[list_id])

【问题讨论】:

    标签: django mptt


    【解决方案1】:

    我通过 template_tag 只找到了一种解决方案

    @register.filter()
    def filter_GET(node, GET):
        qs = node.product_set.all().prefetch_related('product_set')
    
        product = GET.get('product', None)
        if product:
            qs = qs.filter(product_id=product)
    
        any_more = GET.get('any_more', None)
    
        return qs
    

    在模板中

    {% for n in node|filter_GET:request.GET %}
    

    【讨论】:

      猜你喜欢
      • 2010-10-11
      • 2012-10-13
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      相关资源
      最近更新 更多