1

Is there any way to change the ordering of search results when using search_fields in your admin.py?

Here is what I have so far:

# models.py

class Book(models.Model):
    # ...
    name = models.CharField(...)
    description = models.TextField(...)

and:

#admin.py

class BookAdmin(admin.ModelAdmin):
    # ...
    search_fields = ('name', 'description')

Then when I search something in the admin page django aggregate many results from both name and description and returns it in an order which I can't find out. I simply want to sort the results from name before the ones from description.

Is there anyway to do this in django?

VahidM
  • 287
  • 1
  • 2
  • 14

1 Answers1

3

You can specify the default order of a model in a list using the Meta options, the admin uses this to order the instances:

class Book(models.Model):
    #...
    class meta:
        ordering = ['name', 'description']

You could also try setting the ordering in the admin, directly:

class BookAdmin(admin.ModelAdmin):
    # ...
    search_fields = ('name', 'description')
    ordering = ['name', 'description']

Update based on your comment:

If you want to only affect the order of the results, you could intercept the QuerySet that brings you the results like so:

class BookAdmin(admin.ModelAdmin):
    # ...
    search_fields = ('name', 'description')

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(BookAdmin, self).get_search_results(request, queryset, search_term)
        queryset = queryset.order_by('name', 'description')
        return queryset, use_distinct

Although the result of that operation could be ordered again later in the process, that is what would give you an ordered result list.

fixmycode
  • 8,220
  • 2
  • 28
  • 43
  • Thank you, but this is not what I'm looking for. Consider I have another field `last_modified` and I want my default ordering to be on that, but when I search for something I want search results to be ordered like what I said in the question. – VahidM Jul 06 '14 at 07:44
  • @VahidM I've updated my answer with another method that applies only to the results – fixmycode Jul 10 '14 at 18:36
  • Sorry for late response. you're solution works just fine with in django 1.6 and we are currently on 1.3, but we are going to migrate to 1.6 as soon as possible, so you answer is right and solves the problem. but what can be done in 1.3? – VahidM Jul 30 '14 at 22:29
  • 1
    That method was added in 1.6, I read the whole 1.6 implementation of `get_search_results()` and the way it is used in the Admin views, and I don't see a way you could use it on 1.3 without creating your own admin views, and that would defeat the purpose of using contrib.admin, migrating your app is the safest bet. – fixmycode Aug 01 '14 at 06:26