Django 中的列表视图 //编辑

问题描述

我正在使用基于类的视图并希望使用 ListView 在网页上显示数据。正在使用 for 循环来显示许多对象数据。在我的模型中,商品有一个 category 字段,即 ForeignKey,其中类别是 Bags、Tshirts 或 Shoes。我只想显示类别为鞋类的商品。我曾尝试使用不适用于 ForeignKey 字段的 if 条件。如何过滤 Category 字段以仅显示 Bags?

models.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' %}
...

您正在将 Category 对象与字符串 Bags 进行比较。

//编辑

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