ListView in Django



我正在使用基于类的视图,并希望使用ListView在网页上显示数据。我使用for循环来显示许多对象数据。在我的模型中,物品有一个类别字段,该字段为ForeignKey,其中类别为Bags、Tshirts或Shoes。我想显示类别为"仅限鞋子"的项目。我尝试过使用if条件,但它不适用于ForeignKey字段。如何过滤"类别"字段以仅显示"行李"?

型号.py

from django.db import models
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length=30)
createdtime = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "Categories"
class Product(models.Model):
mainimage = models.ImageField(upload_to='product')
name = models.CharField(max_length=264)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category')
previewtext = models.TextField(max_length=200, verbose_name='Preview Text')
detailstext = models.TextField(max_length=1000, verbose_name='Description')
price = models.FloatField()
oldprice = models.FloatField(default=0.00)
createddate = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Meta:
ordering = ['-createddate',]

views.py

from django.shortcuts import render
from django.views.generic import ListView, DetailView
from shopapp.models import Product
# Create your views here.
class Home(ListView):
model = Product
template_name = 'shopapp/home.html'

html文件

<div class="container my-5">
<h2 class="my-5">Handbags</h2>
<div class="row">
{% for product in object_list %}
{% if product.category == 'Bags' %}
<div class="col-md-6 col-sm-12 col-lg-3">
<figure class="card card-product">
<div class="img-wrap">
<a href="{% url 'shopapp:productdetail' pk=product.pk %}"><img src="/media/{{ product.mainimage }}" style="width:100%; height:300px;"></a>
</div>
<figcaption class="info-wrap">
<h6 class="title">{{ product.name }}</h6>
<div class="action-wrap">
<div class="price-wrap h5">
<span class="price-new">${{ product.price|floatformat:2 }}</span>
<span class="price-old"><strike>${{ product.oldprice|floatformat:2 }}</strike></span>
</div>
</div>
</figcaption>
</figure>
</div>
{% endif %}
{% endfor %}
</div>
</div>

在代码中使用product.category.title,如下所示:

...
{% if product.category.title == 'Bags' %}
...

您正在将类别对象与字符串行李进行比较。

//编辑

如果您只需要视图中的数据,我还建议您过滤视图中的这些数据。不需要从数据库中获取所有产品并将其发送到视图,只需渲染其中的一部分

最新更新