In this tutorial I will show you how to solve this following error "Related Field got invalid lookup: icontains" in django python project.
CODE: admin.py
from django.contrib import admin
from .models import *
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'description')
list_per_page=10
search_fields=['name','category'] admin.site.register(Product, ProductAdmin)
Model.py:
class Category(models.Model):
name=models.CharField(max_length=150,null=False,blank=False)
image=models.ImageField(upload_to=getFileName,null=True,blank=True)
description=models.TextField(max_length=500,null=False,blank=False)
created_at=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Product(models.Model):
category=models.ForeignKey(Category,on_delete=models.CASCADE)
name=models.CharField(max_length=150,null=False,blank=False)
product_image=models.ImageField(upload_to=getFileName,null=True,blank=True)
description=models.TextField(max_length=500,null=False,blank=False)
created_at=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
This error is happening due to adding foreign key field in search_fields.
To Resolve this error:
To add foreign key field in search, use double-underscore and grab name field from the category model.
EDITEDED CODE:admin.py
from django.contrib import admin
from .models import *
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'description')
list_per_page=10
search_fields=['name','category__name'] admin.site.register(Product, ProductAdmin)
VIDEO GUIDE: