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:
Post your comments / questions
Recent Article
- How to add two numbers in Android Studio? | Source Code
- FindViewByID returns null in android studio -SOLVED
- Saving changes is not permitted in SQL SERVER - [SOLVED]
- Restore of database failed. File cannot be restored over the existing. -[SOLVED]
- One or more projects in the solution were not loaded correctly in Visual Studio 2019 | FIXED
- How to find Laptop's Battery Health?
- How to enable Search Feature in Django admin?
- How to check PAN-Aadhaar is Linked or NOT?
Related Article