I have a django model, called "User" which stores some basic information about people, namely first and last name. I currently have a simple search across my django model where, if a user types in a first name, The django queryset returns the first 10 matches, ordered by last name.
For example, currently, if you search for "Sam" you might get the following results:
- Sam Abbott
- Samuel Baker
- Sammy Rogers
- Sam Simmons
The code for this is simple:
User.objects.filter(Q(first__istartswith=token)).order_by('last')
However, I want to alter this so that any exact first name matches are returned first, followed by the rest of the results. So if someone types in "Sam", the results should instead be:
- Sam Abbott
- Sam Simmons
- Samuel Baker
- Sammy Rogers
(Exact first name matches first, sorted by last name, followed by the rest of the matches sorted by last name).
I thought about turning this into 2 querysets and then just combining the lists, but I was wondering if it was possible to do this in 1 query, ideally sticking with the basic django queryset API (rather than writing a one-off query). Does anyone know a way to do that?
Thanks in advance.