简体   繁体   中英

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

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)

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

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)

in views

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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