在django admin中搜索相关字段

时间:2014-07-04 08:16:32

标签: python django relational-database

我在django admin中一直在the docs查看search_fields以尝试搜索相关字段。

所以,这是我的一些模特。

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

我想要的是YearRecord管理员能够搜索跑步者所属的团队。但是,只要我尝试将Runner FK关系添加到搜索字段,我就会在搜索时出错; TypeError: Related Field got invalid lookup: icontains

所以,这里是管理员设置,我希望能够搜索关系。我确定这与文档匹配,但我在这里误解了什么吗?这可以解决吗? result__runner是否会扩展到Runner模型的团队字段?

# 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 个答案:

答案 0 :(得分:23)

文档内容如下:

这些字段应为某种文字字段,例如CharFieldTextField

所以你应该使用'result__runner__team__name'