Emmanuel Osimosu
Emmanuel Osimosu

Reputation: 6004

Add a choicefield to search_fields in django admin

Say, I have a model with a choice field that looks like this:

STARTED = 1
DONE = 0

STATUSES = {
    (STARTED, 'Started'),
    (DONE, 'Done'),
}

status = models.IntegerField(choices=STATUSES)

I'd like to add the field status to search_fields = () in admin.py like below.

search_fields = (status,)

It works searching by integer but I'd like to search based on the display text "Done" and "Started."

Upvotes: 0

Views: 2112

Answers (1)

Alasdair
Alasdair

Reputation: 308899

You should be able to do this by overriding the get_search_results method of your model admin.

# This dictionary lets you convert the text back to the integer.
# You might prefer to build it dynamically instead.

TEXT_TO_STATUS_INTEGER = {
    'Started': 1,
    'DONE': 0,
}

class MyModelAdmin(admin.ModelAdmin):
    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
        if search_term in TEXT_TO_STATUS_INTEGER:
            queryset |= self.model.objects.filter(status=TEXT_TO_STATUS_INTEGER[search_term])
    return queryset, use_distinct

Upvotes: 1

Related Questions