Reputation: 397
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?
Upvotes: 1
Views: 1199
Reputation: 8506
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.
Upvotes: 3