Django admin search function in GenerifForeignkey field with Content_object relation

I am trying to build an admin page that lets admins search through 2 fields of the model "SeasonalitiesCalculated". The fields for my search are called "fruit" and "object_id".

"fruit" is a Foreignkey field and returns the "name" field of the corresponding fruit.

"object_id" is Genericforeignkey field that sometimes points at a UUID in a model called "Countries" (with a "country_name" field: Germany) and sometimes points at a UUID in a model called "AdminZones" (with an "admin_zone_name" field: California)

The problem now is that django seems to not have any standard way of searching through GenericForeignkeys. So I tried defining a search function like this:

class SeasonalitiesCalculatedAdmin(admin.ModelAdmin):

    list_per_page = 20

    def country_or_admin_zone_name(self, obj):
        return obj.country_or_admin_zone_name()

    country_or_admin_zone_name.short_description = 'Country or Admin Zone'

    def search_field(self, obj):
        return obj.search_field()

    list_display = ('fruit', 'country_or_admin_zone_name', 'content_type', ...)

    search_fields = ('fruit__fruit_name', 'search_fields')

the admin page itself works and it also shows the country or admin zone names and other foreignkey related fields properly since I specified this in the SeasonalitiesCalculated model like this

class SeasonalitiesCalculated(LoggingMixinSeasons, Basemodel):
    fruit = models.ForeignKey('IngredientOriginals', on_delete=models.PROTECT, related_name='%(class)s_related_ingredient_original')

    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
    object_id = models.UUIDField(default=uuid.uuid4, editable=False)
    content_object = GenericForeignKey('content_type', 'object_id')
    class Meta:
        managed = True
        db_table = 'seasonalities_calculated'
        verbose_name_plural = 'Seasonalities Calculated'
        constraints = [models.UniqueConstraint(fields=['ingredient_original_id', 'content_type_id', 'object_id',], name='unique_seasonalities_calculated')]

    def country_or_admin_zone_name(self):
        content_object = self.content_object
        if isinstance(content_object, Countries):
            return content_object.country_name
        elif isinstance(content_object, AdminZones1):
            return content_object.admin_zone_1_name
            return None

    def search_field(self):
        content_object = self.content_object
        if isinstance(content_object, Countries):
            return 'content_object__country_name'
        elif isinstance(content_object, AdminZones1):
            return 'content_object__admin_zone_1_name'
        return None

but i just cant figure out how to make the search_fields work becuase of the content object relation.

i tried overriding the standard search query but without success...

any help is much appreciated

Back to Top