У меня есть главная таблица Item, которая связана с табличной меткой с отношением «многие ко многим». Я хотел бы отобразить метку в представлении, но это не работает. Я пробовал item.label.name, который дает значение None
, а item.label дает core.Label.None
. Как правильно отобразить метку?
views.py
def HomeView(request):
item_list = Item.objects.all()
item_list = item_list.annotate(
current_price=Coalesce('discount_price', 'price'))
category_list = Category.objects.all()
label_list = Label.objects.all()
query = request.GET.get('q')
if query:
item_list = item_list.filter(title__icontains=query)
cat = request.GET.get('cat')
if cat:
item_list = item_list.filter(category__pk=cat)
price_from = request.GET.get('price_from')
price_to = request.GET.get('price_to')
if price_from:
item_list = item_list.filter(current_price__gte=price_from)
if price_to:
item_list = item_list.filter(current_price__lte=price_to)
paginator = Paginator(item_list, 10)
page = request.GET.get('page')
try:
items = paginator.page(page)
except PageNotAnInteger:
items = paginator.page(1)
except EmptyPage:
items = paginator.page(paginator.num_pages)
context = {
'items': items,
'category': category_list,
'label': label_list
}
return render(request, "home.html", context)
hmtl template:
{% for item in items %}
<div class="col-lg-3 col-md-6 mb-4">
<div class="card">
<div class="view overlay">
<img src="{{ item.image.url }}" class="card-img-top">
<a href="{{ item.get_absolute_url }}">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body text-center">
<h5>
<strong>
<a href="{{ item.get_absolute_url }}" class="dark-grey-text">{{ item.title }}
<span class="badge badge-pill "></span>
<p>{{ item.label }}</p>
</a>
</strong>
</h5>
<h4 class="font-weight-bold blue-text">
<strong>
{% if item.discount_price %}
<strike>£{{ item.price }}</strike> £{{ item.discount_price }}
{% else %}
£{{ item.price }}
{% endif %}
</strong>
</h4>
</div>
</div>
</div>
{% endfor %}
models.py
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
discount_price = models.FloatField(blank=True, null=True)
category = models.ManyToManyField(Category, blank=True)
label = models.ManyToManyField(Label, blank=True)
slug = models.SlugField()
description = models.TextField()
image = models.ImageField()
class Label(models.Model):
name = models.CharField(max_length=20)