Reputation: 385
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)
Upvotes: 2
Views: 3889
Reputation: 29
Model:
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)
View:
status1=request.POST.get("status")
response1=order.objects.filter(status__contains=status1)
Upvotes: 0
Reputation: 5993
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
Upvotes: 2