models.py
from django.db import models
from django.urls import reverse
class Category(models.Model):
category_id = models.AutoField
category_name = models.CharField(max_length=50, default="")
desc = models.CharField(max_length=1000)
slug = models.SlugField(max_length=20)
image = models.ImageField(upload_to='onlinePizza/images', default="")
def get_url(self):
return reverse('category', args=[self.slug])
def __str__(self):
return self.category_name
class Product(models.Model):
product_id = models.AutoField
product= models.CharField(max_length=50)
category = models.ForeignKey(Category, default='', null=True, on_delete=models.CASCADE)
desc = models.CharField(max_length=1000)
image = models.ImageField(upload_to='onlinePizza/image', default="")
def __str__(self):
return self.product
This is my views.py file. I show error at
bestseller = Product.objects.filter(product__category__icontains='BestSeller')
views.py
from django.shortcuts import render
from . models import Category, Product, Deal
from math import ceil
def index(request):
bestseller = Product.objects.filter(product__category__icontains='BestSeller')
context = {'bestseller':bestseller}
return render(request, 'onlinePizza/index.html', context)
I want to Bestseller category product at index.html
I use Django 4 and pyhton 3.9
CodePudding user response:
you can't use charfield as a foreing key field,
it should be like this:
bestseller = Product.objects.filter(category__category_name ='BestSeller')
or like this (the same logic):
best_seller_category = Category.objects.get(category_name = "BestSeller")
bestseller = Product.objects.filter(category=best_seller_category)
this will output all Products
in category with name BestSeller