i am getting this error when i try to search in admin panel

1,825 views
Skip to first unread message

Ravindra Magar

unread,
May 18, 2023, 7:01:54 AM5/18/23
to django...@googlegroups.com
i am getting this error when i try to  search in admin panel

FieldError at /admin/school/center/
Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted.

admin.py
@admin.register(Center)
class CenterAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    list_display = ('id', 'state', 'district', 'taluka', 'center',)
    list_filter = ('state', 'district', 'taluka','center')
    search_fields = ('state','district', 'taluka','center',)

model.py
class Center (models.Model):

       state = models.ForeignKey(State, on_delete=models.CASCADE)
       district = ChainedForeignKey(District,
                              chained_field='state',
                              chained_model_field='state',show_all=False,  auto_choose=True,  sort=True)
       taluka = ChainedForeignKey(Taluka,
                              chained_field='district',
                              chained_model_field='district',show_all=False, auto_choose=True,  sort=True)


       center = models.CharField(max_length=200)

       def str(self):
            return self.center

Brian Gitau

unread,
May 18, 2023, 9:44:36 AM5/18/23
to django...@googlegroups.com
The issue lies in specifying ForeignKey fields (state, district, and taluka) within the search_fields. ForeignKey fields cannot be searched using 'icontains' because it requires a direct string comparison. Instead, you can search based on the related field's attributes.

To resolve the error, you need to change the search_fields attribute to search based on related fields' attributes. Assuming State, District, and Taluka models have a field named name, you can update the search_fields as follows:

search_fields = ('state__name', 'district__name', 'taluka__name', 'center',)

This modification will search for the related fields' name attributes, allowing you to perform a case-insensitive substring search on those fields.

Remember to import the related models (State, District, and Taluka) at the top of your admin.py file for the updated search_fields to work correctly.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAHMymCAkUmAc%3DGiG2mxmfNJLbT%3DYY7XwtCqsdE5m4M_Lr-hfVA%40mail.gmail.com.

ivan harold

unread,
Aug 9, 2023, 2:16:23 PM8/9/23
to Django users
was this issue resolved already?
Reply all
Reply to author
Forward
0 new messages