Django管理站点自定义search_fields查询

发布于 2024-09-06 03:47:22 字数 265 浏览 2 评论 0原文

在 django 管理中,您可以设置 ModelAdmin 的 search_fields 以便能够搜索那里给出的属性。我的模型类有一个不是真正模型属性的属性,这意味着它不在数据库表中。该属性与另一个数据库表相关,该数据库表未通过关系与当前模型绑定。 但我希望能够对其进行搜索,因此我必须以某种方式自定义管理站点创建的查询,以便在填充搜索字段时进行过滤 - 这是否可能,如果,如何? 我可以查询自定义属性的数据库表,然后它返回适合搜索的模型类的 ID。正如我所说,这必须流入管理站点搜索查询。

谢谢!

In the django admin you can set the search_fields for the ModelAdmin to be able to search over the properties given there. My model class has a property that is not a real model property, means it is not within the database table. The property relates to another database table that is not tied to the current model through relations.
But I want to be able to search over it, so I have to somehow customize the query the admin site creates to do the filtering when the search field was filled - is this possible and if, how?
I can query the database table of my custom property and it then returns the ids of the model classes fitting the search. This then, as I said, has to flow into the admin site search query.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

从 django 1.6 开始,您可以通过在 ModelAdmin 子类中定义 get_search_results 方法来自定义搜索。

django 文档中对此进行了很好的解释< /a>.以下示例是从此文档复制的。

class PersonAdmin(admin.ModelAdmin):
    list_display = ('name', 'age')
    search_fields = ('name',)

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
        try:
            search_term_as_int = int(search_term)
            queryset |= self.model.objects.filter(age=search_term_as_int)
        except:
            pass
        return queryset, use_distinct

Since django 1.6, you can customize the search by defining a get_search_results method in your ModelAdmin subclass.

It is well explained in django documentation. The following example is copied from this doc.

class PersonAdmin(admin.ModelAdmin):
    list_display = ('name', 'age')
    search_fields = ('name',)

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
        try:
            search_term_as_int = int(search_term)
            queryset |= self.model.objects.filter(age=search_term_as_int)
        except:
            pass
        return queryset, use_distinct
╭⌒浅淡时光〆 2024-09-13 03:47:22

您应该使用 search_fields = ['foreign_key__lated_fieldname']
就像扩展 admin.ModelAdmin 的管理类中的 search_fields = ['user__email']

阅读更多 此处

You should use search_fields = ['foreign_key__related_fieldname']
like search_fields = ['user__email'] in the admin class that extends admin.ModelAdmin

read more here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文