我的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种产品,但我想过滤可用的产品。
我应该过滤视图类中的产品并传递给单独的Queryset进行模板过滤的产品对象,还是应该在模板中应用所有过滤器?
如果我应该像上面尝试的那样在模板中过滤它们,是否有任何方法可以根据它们的可用性来过滤产品对象?
谢谢
答案 0 :(得分:0)
class ProductManager(models.Manager):
def is_available(self):
return self.get_queryset().filter(is_available=True)
class Product(models.Model):
--------
objects = ProductManager()
views.py
product = Product.objects.is_available()
return render(request, 'shop/shopping.html', {'products' : product})
模板
{% for product in products %}
{{ product.name }}
{% for item in product.category.all %}
{{ item.name }}
{% endfor %}{% endfor %}
答案 1 :(得分:0)
from ..models import ProductCategories
from django import template
register = template.Library()
@register.filter
def is_available(value, arg):
products = value.filter(is_available = arg)
return products
并在您的HTML中这样使用:
{% load app_tags %}
...
...
...
{% with products=category.product.all|is_available:True %}
...
...
请尝试此解决方案。希望对您有帮助。