在django admin中搜索相关字段

时间:2020-12-17 11:45:35

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

我一直在检查django admin中的search_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

我想让年度记录管理员能够搜索一个跑步者所属的队。但是,当我尝试将Runner FK关系添加到搜索字段时,我在搜索中会得到一个错误;TypeError:相关字段的查找无效:icontain

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?

这是管理设置,我想在这里搜索关系。我确定这和文档是一致的,但是我有什么误解吗?可以解决这个问题吗?结果__runner可以扩展到Runner模型的team字段中吗?

# 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")

1 个解决方案

#1


23  

The documentation reads:

文档写着:

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

这些字段应该是某种文本字段,比如CharField或TextField。

so you should use 'result__runner__team__name'.

所以你应该使用“result__runner__team__name”。

#1


23  

The documentation reads:

文档写着:

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

这些字段应该是某种文本字段,比如CharField或TextField。

so you should use 'result__runner__team__name'.

所以你应该使用“result__runner__team__name”。