在Django管理中按相关字段搜索 [英] Searching by related fields in django admin

查看:65
本文介绍了在Django管理中按相关字段搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在查看文档 search_fields 来尝试搜索相关字段。

I've been looking at the docs for search_fields in django admin in the attempt to allow searching of related 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:相关字段的查找无效:​​icontains

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

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

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


推荐答案

文档内容为:

这些字段应为某种文本字段,例如 CharField TextField

应该使用'result__runner__team__name'

这篇关于在Django管理中按相关字段搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆