Reputation: 61
I am getting this error django.core.exceptions.FieldError: Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted
Below is models.py:
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Book(models.Model):
title = models.CharField(max_length=100)
rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
author = models.ForeignKey(Author,on_delete=models.CASCADE,null=True)
is_bestselling = models.BooleanField(default=False)
slug = models.SlugField(default="",null=False,blank=True)
def get_absolute_url(self):
return reverse("model_detail", args=[self.slug])
def __str__(self):
return self.title
Below is admin.py:
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'rating', 'author','is_bestselling',)
list_display_links = ('title', 'rating',)
search_fields = ('title', 'rating','author',)
list_filter = ('rating', 'is_bestselling',)
prepopulated_fields = {
'slug': ('title',)
}
class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name',)
list_display_links = ('first_name', 'last_name',)
search_fields = ('first_name', 'last_name',)
I was trying to search Author in my Books Model.
Upvotes: 5
Views: 14914
Reputation: 18691
For me the error was due to the use of a field in Django admin's search_fields
(for use on the list page) while the field was part of exclude
as well (to avoid showing it on the detail page). This isn't compatible so had to remove the field from search_fields
as well.
Upvotes: 1
Reputation: 309
The error you are encountering can be attributed to the utilization of the default search option in Django within your admin.py
file.
Django's search option is designed to exclusively search for a field in the database, based on the column name rather than a table or row name.
To rectify this error, you have two potential solutions:
from django.contrib import admin
from . import models
@admin.register(models.Post)
class PostModelAdmin(admin.ModelAdmin):
...
search_fields = ('title', 'body', 'author__username')
...
Upvotes: 13