I am getting this error django.core.exceptions.FieldError: Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted
Asked Answered
W

2

5

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.

Wonted answered 5/6, 2023 at 12:42 Comment(2)
You should post the answer in the answer section (below) not include it in the question.Chronic
Ohk Sure @Willem Van OnsemWonted
P
12

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:

  1. Conduct a search within one or two columns of the User model:
from django.contrib import admin
from . import models

@admin.register(models.Post)
class PostModelAdmin(admin.ModelAdmin):
    ...
    search_fields = ('title', 'body', 'author__username')
    ...
  1. Alternatively, eliminate the author search functionality.
Pontormo answered 17/8, 2023 at 9:13 Comment(0)
R
1

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.

Radiotelegraphy answered 6/7 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.