c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
Python

SOLVED-Related Field got invalid lookup: icontains error in Django

| | python

In this tutorial I will show you how to solve this following error "Related Field got invalid lookup: icontains" in django python project.

FieldError in django admin

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: