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
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
- FieldError: Cannot resolve keyword 'id' into field in Django project
Related Article