Django'objects.filter()'无法正常工作吗?

时间:2020-07-20 13:37:07

标签: python django web

我正在尝试根据类别过滤产品,但是Listing.object.filter(category = category)无法根据需要过滤,并且每次都返回

在views.py的底部代码上,该函数是带有参数的category和category。 也许我这边有些逻辑上的错误, 任何帮助将不胜感激。

这是我的代码:

这是我的模特。py

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.conf import settings

CATEGORY_CHOICES = (
    ('MC','Mens Clothing'),
    ('WC','Womens Clothing'),
    ('G','Games'),
    ('T','Tech'),
    ('BP','Beauty Products'),
    ('O','Others'),
)

class User(AbstractUser):
    pass

class Listing(models.Model):
    title = models.CharField(max_length = 100)
    price = models.FloatField()
    description = models.TextField()
    image = models.URLField(blank = True)
    time = models.DateTimeField(auto_now_add=True)
    category = models.CharField(choices = CATEGORY_CHOICES, max_length = 2)
    winner = models.ForeignKey(User, on_delete=models.CASCADE, null = True, blank = True, related_name="winner")
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    availability = models.BooleanField(default=True)

    def __str__(self):
        return self.title

我的views.py


def index(request):
    items = Listing.objects.filter(availability = True)
    category_list = []
    for d,k in CATEGORY_CHOICES:
        category_list.append(k)
    context = {
        'items': items,
        'title': "Active Listing",
        'categories': category_list
    }
    return render(request, "auctions/index.html", context)

def categories(request):
    data = []
    for d,k in CATEGORY_CHOICES:
        data.append(k)
    context = {
        'categories': data
    }
    return render(request, "auctions/categories.html", context)

def category(request, category):
    data = Listing.objects.filter(category = category, availability = True)
    if len(data) != 0:
        context = {
            'items': data,
            'title': category
        }
        return render(request, "auctions/index.html", context)
    else:
        context = {
            'title': "EMPTY",
        }
        return render(request, "auctions/index.html", context)

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试一下:

在您的index.py

中进行更改
for d,k in CATEGORY_CHOICES:
    category_list.append(d)