Searching by related fields in django admin

markwalker_ picture markwalker_ · Jul 4, 2014 · Viewed 13.8k times · Source

I've been looking at the docs for search_fields in django admin in the attempt to allow searching of related fields.

So, here are some of my models.

# models.py
class Team(models.Model):
    name = models.CharField(max_length=255)


class AgeGroup(models.Model):
    group = models.CharField(max_length=255)


class Runner(models.Model):
    """
    Model for the runner holding a course record.
    """
    name = models.CharField(max_length=100)
    agegroup = models.ForeignKey(AgeGroup)
    team = models.ForeignKey(Team, blank=True, null=True)


class Result(models.Model):
    """
    Model for the results of records.
    """
    runner = models.ForeignKey(Runner)
    year = models.IntegerField(_("Year"))
    time = models.CharField(_("Time"), max_length=8)


class YearRecord(models.Model):
    """
    Model for storing the course records of a year.
    """
    result = models.ForeignKey(Result)
    year = models.IntegerField()

What I'd like is for the YearRecord admin to be able to search for the team which a runner belongs to. However as soon as I attempt to add the Runner FK relationship to the search fields I get an error on searches; TypeError: Related Field got invalid lookup: icontains

So, here is the admin setup where I'd like to be able to search through the relationships. I'm sure this matches the docs, but am I misunderstanding something here? Can this be resolved & the result__runner be extended to the team field of the Runner model?

# admin.py
class YearRecordAdmin(admin.ModelAdmin):
    model = YearRecord
    list_display = ('result', 'get_agegroup', 'get_team', 'year')
    search_fields = ['result__runner', 'year']

    def get_team(self, obj):
        return obj.result.runner.team
    get_team.short_description = _("Team")

    def get_agegroup(self, obj):
        return obj.result.runner.agegroup
    get_agegroup.short_description = _("Age group")

Answer

Germano picture Germano · Jul 4, 2014

The documentation reads:

These fields should be some kind of text field, such as CharField or TextField.

so you should use 'result__runner__team__name'.