0

I am trying to filter my products based on the categories but the Listing.object.filter(category = category) is not able to filter as desired and return EMPTY every time.

On the bottom code at views.py where the function is category with an argument as well category. Maybe there is some logical error from my side, any help would be appreciated.

Here is my code:

Here is my models.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

My 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

4

1 回答 1

0

尝试这个:

在你的index.py

for d,k in CATEGORY_CHOICES:
    category_list.append(d)
于 2020-07-20T13:44:13.070 回答