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
- ImportError: cannot import name 'url' from 'django.conf.urls' - Django Error
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
- Remove all special characters, punctuation except spaces from string - Python
- OSError: cannot write mode RGBA as JPEG- Python
Related Article