Skip to content

Unsupported lookup ‘category’ for CharField or join on the field not permitted

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 file. I show error at:

bestseller = Product.objects.filter(product__category__icontains=’BestSeller’)

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



You can’t use CharField as a ForeignKey.

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.

3 People found this is helpful