简体   繁体   English

search_field 按字段选择

[英]search_field by field choice

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" ?我有一个基本的 django 模型,我想知道有没有办法让搜索字段在我映射到的值中搜索,而不是在数据库中保存的值中搜索,是否有一种可能的方法可以通过价值“溢价”?

Model.py模型.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)

Summary from comments discussion; 评论讨论摘要;

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 https://github.com/sivaa/django-custom-search-filter/blob/master/app/admin.py

class order(models.Model):类顺序(模型。模型):

STATUS = (
    ("Completed", "Completed"),
    ("Ordered", "Ordered"),
    ("Accepted", "Accepted"),
    ("Order Cancel", "Order Cancel"),
    ("Customer Cancel", "Customer Cancel"),
    ("Delivered", "Delivered"),
    ("Added to Cart", "Added to Cart"),
    ("Out of Delivery", "Out of Delivery"),
    ("Refund Initiated","Refund Initiated"),
    ("Return And exchange","Return And exchange"),
    
)

status = models.CharField(default="Ordered",max_length=50,null=True, choices=STATUS,blank=True) status = models.CharField(default="Ordered",max_length=50,null=True,choices=STATUS,blank=True)

in views在视图中

status1=request.POST.get("status") status1=request.POST.get("状态")

response1=order.objects.filter(status__contains=status1) response1=order.objects.filter(status__contains=status1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM