我一直在做这个项目我想按类别ID名称过滤all_products,但是当我这样做时,它给了我错误形成的十六进制UUID字符串错误。 这是models.py
from django.db import models
import uuid
# Create your models here.
class Category(models.Model):
category = models.CharField(max_length=100)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.category
class Product(models.Model):
title = models.CharField(max_length=100)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
image = models.FileField(default=None)
desc = models.TextField(default="Random")
price = models.DecimalField(max_digits=10, decimal_places=2)
vnos = models.CharField(max_length=30)
quantity = models.BigIntegerField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
times_bought = models.BigIntegerField(default=0)
def __str__(self):
return self.title
和views.py
def category_detail(request, category_id):
try:
current_category = Category.objects.get(pk=category_id)
except Product.DoesNotExist:
raise Http404("Album does not exist.")
current_category_name = current_category.category
template = loader.get_template('categories/details.html')
all_products = Product.objects.all()
products_by_category = Product.objects.all().filter(category=str(current_category_name))
footer = loader.get_template('main/footer.html')
head = loader. get_template('main/head.html')
nav = loader.get_template('main/nav.html')
all_categories = Category.objects.all()
paginator = Paginator(all_products, 6)
page = request.GET.get('page')
try:
all_products = paginator.page(page)
except PageNotAnInteger:
all_products = paginator.page(1)
except EmptyPage:
all_products = paginator.page(paginator.num_pages)
context = {
'all_products': all_products,
'all_categories': all_categories,
'footer': footer,
'head': head,
'nav': nav,
'products_by_category': products_by_category
}
return HttpResponse(template.render(context, request))
我尝试了不同的方法,但没有什么真正有用。我想点击某个链接时按类别名称过滤产品。
当我试图激怒变量时会引发错误。
{% for product in products_by_category %}
如果我不在products_by_category上使用过滤器,它运行正常。
答案 0 :(得分:1)
按类别过滤Product
模型时,应使用类别实例,而不是类别名称。
products_by_category = Product.objects.filter(category=current_category)
请注意,您不需要在all()
之前致电filter()
。