search_field(按字段选择) [英] search_field by field choice

查看:45
本文介绍了search_field(按字段选择)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的django模型,我想知道是否有一种方法可以使搜索字段在要映射的值中进行搜索,而不是在数据库中保存的值中进行搜索,有没有一种可能的方法通过值"Premium"搜索?

I've a basic django model and i was wondering is there a way to make the search fields search in the value i am mapping to instead of searching in the value saved in the database, is there a possible way that i can search by the value "Premium" ?

Model.py

class User(models.Model):
    account = models.ForeignKey('Account')
    name =models.CharField(max_length=50)
    ACCOUNT_CHOICES = (
       (1, 'Premium'),
       (0, 'Normal'),)
    type = models.CharField(choices=ACCOUNT_CHOICES)

Admin.py

class UserAdmin(admin.ModelAdmin):
     search_fields = ['name','type']
    pass
admin.site.register(User,UserAdmin)

推荐答案

评论讨论摘要;

您需要为搜索过滤器设置一个自定义查询集,以尝试将选择显示字段反向查找为其值.另一个小问题是,多个值可以具有相同的选择显示名称,因此您需要考虑这一点.

You'll need to set up a custom queryset for the search filter which attempts to reverse lookup the choice display field to its value. Another slight issue is that multiple values can have the same choice display name, so you'll need to take that into consideration.

以下是如何实现此目的的示例:

Here is an example of how to achieve this:

https://github.com/sivaa/django-custom-search-filter/blob/master/app/admin.py

这篇关于search_field(按字段选择)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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