【发布时间】:2020-04-09 20:16:07
【问题描述】:
我的 HTML
{% for category in categories %}
<div class="row">
<h3 style="padding-left: 15px; padding-bottom: 15px">{% filter upper %}{{ category.name }}{% endfilter %}</h3>
</div>
<div class="row">
{% with products=category.product.all|is_available:True %}
{% for product in products|slice:":4" %}
<div class="product-width col-xl-3 col-lg-3 col-md-3 col-sm-6 col-12 mb-30">
<div class="product-wrapper">
<div class="product-img">
<a href="{% url 'shop:product' category.name product.id %}">
<img alt="" src="{{product.image.all.0.image.url }}">
</a>
<div class="product-action">
<a class="action-wishlist" href="#" title="Wishlist">
<i class="ion-android-favorite-outline"></i>
</a>
<a class="action-cart" href="#" title="Add To Cart">
<i class="ion-android-add"></i>
</a>
</div>
</div>
<div class="product-content text-left">
<div class="product-title">
<h4>
<a href="{% url 'shop:product' category.name product.id %}">{{ product.name|title }}</a>
</h4>
</div>
<div class="product-price-wrapper">
<span>{{product.price}} TL</span>
</div>
</div>
</div>
</div>
{% endfor %}
{% endwith %}
</div>
<div class="row justify-content-end">
<a href="{% url 'shop:category' category.name %}">Daha Fazla...</a>
</div>
{% endfor %}
我的模特
每个产品与类别具有多对多关系,并且产品也有一个 is_available 变量。
class ProductCategories(models.Model):
name = models.CharField(max_length = 60)
image = models.ImageField(upload_to = 'ProductCategories')
publish_date = models.DateTimeField(auto_now=False, auto_now_add=True)
is_available = models.BooleanField()
class Product(models.Model):
category = models.ManyToManyField(ProductCategories, related_name="product")
name = models.CharField(max_length = 60)
price = models.DecimalField(max_digits=65, decimal_places=2)
description = models.TextField()
publish_date = models.DateTimeField(auto_now=False, auto_now_add=True)
stock_number = models.IntegerField()
is_available = models.BooleanField()
我的观点
categories = ProductCategories.objects.all()
return render(request, 'shop/shopping.html', {'categories' : categories})
我在每个类别下列出 4 个产品,但我想过滤可用的产品。
我应该在视图类中过滤产品并将过滤后的产品对象单独的查询集传递给模板,还是应该在模板中应用所有过滤器?
如果我应该像上面尝试的那样在模板中过滤它们,有没有办法根据产品对象的可用性过滤它们?
谢谢,
【问题讨论】:
-
请不要在模板中过滤,而是在视图中。
-
我应该将两个单独的对象(类别和过滤产品)传递给模板,还是有什么方法可以过滤类别查询集中的产品?
-
您可以在模型或视图中添加过滤器,is_available=True
标签: python django django-models django-templates django-views