如何根据外键过滤对象

问题描述 投票:0回答:1

我有2个名为product和product_category的模型类

class product_category(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
    category_name = models.CharField(max_length=20, blank=False, null=False, default="")
    slug = models.SlugField(max_length=255, unique=True)


class product(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
    product_name = models.CharField(max_length=50, blank=False, null=False, default="")
    product_description = models.TextField(max_length=280, blank=True, null=True, default="")
    product_type = models.ForeignKey(product_category, related_name='type_category', blank=True, null=True, on_delete=models.CASCADE)
    slug = models.SlugField(max_length=255, unique=True)

在views.py中,这是我通常加载与单个用户相关的所有产品的方式

all_category = product.objects.filter(user=user)

但我正在努力过滤的是基于它们所在类别的产品清单。

如您所见,product_type是可选的,因此某些产品可能没有任何类型。这些产品应列在清单的末尾。

这就是我想在网站上显示的方式

  • 1类 产品1 产品2 产品3
  • 类-2 产品4 产品5 产物-6-
  • 类别-3 产品7
  • 产品8
  • 产品9
  • 产品10

我该怎么做到这一点?

编辑1。

感谢neeraj-kumar,我找到了我想要的东西。

这是他的答案 在代码中更清楚地看到结果。

views.朋友

    all_category = product_category.objects.filter(user=user)
    product_exclude = product.objects.exclude(id__in=all_category.values_list('type_category__id',flat=True)).filter(user=user)

template.html

{% for cat in all_category %}
    {% with products=cat.type_category.all %}
        <h5>{{cat.category_name}}</h5>
        {% if products|length %}
            {% for pro in products %}
                <p>{{ pro }}</p>
            {% endfor %}
        {% endif %}
        <br>
    {% endwith %}
{% endfor %}
{% for pro in product_exclude %}
    <p>{{ pro }}</p>
{% endfor %}
django filter foreign-keys annotate
1个回答
0
投票
all_category = product_category.objects.filter(user=user)
product_exclude = product.objects.exclude(id__in=all_category.values_list('type_category__id',flat=True)

传递模板中的var

{% for cat in all_category %}
   {% with products = cat.type_category.all %}
       {% if products|length %}
            {% for pro in products %}
                {{ pro }}
            {% endfor %}
       {% endif %}
   {% endwith %}
{% endfor %}
{% for pro in product_exclude %}
     {{ pro }}
{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.