Solve django admin search error related fields has invalid lookup: icontains


When we trying to do search in Django admin, suddenly we caught by this error:

1
2
TypeError at /admin/myapp/myappfolder/
Related Field has invalid lookup: icontains

Then we should check that search_fields in DjangoAdmin should be on field rather on ForeignKey objects.
Eg :

1
2
3
4
5
class InsuranceAdmin(admin.ModelAdmin):
    """Set Insurance Configuration in Admin page"""
    list_display = ["country", "subscription", "created", "modified"]
    list_filter = ("country", "subscription")
    search_fields = (‘country’, )

At this example, country is ForeignKey to Country models. When it comes to search_fields, it’s should be fields, so the correct version is :

1
2
3
4
5
class InsuranceAdmin(admin.ModelAdmin):
    """Set Insurance Configuration in Admin page"""
    list_display = ["country", "subscription", "created", "modified"]
    list_filter = ("country", "subscription")
    search_fields = (‘country__name’, )

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.