MarkD
MarkD

Reputation: 4944

django- how would I create a sort for a query to put one specific element first, then remaining by some field?

Specifically, I am looking to get a query of users. My User model has a first_name and last_name field. What I need to do is order the request.user at the top of the results, and the remaining users in alphabetical order by last_name, first_name. The last part is easy:

q = User.objects.all().order_by('last_name', 'first_name')

However I am not sure how to ensure that the request.user is the first result in the query. This is all being done for a django rest framework view, and thus (I believe) I need to have it done through a query which is passed on to the serializer.

Upvotes: 2

Views: 371

Answers (2)

dukebody
dukebody

Reputation: 7185

If you don't really need the result to be a queryset you can try the following:

import itertools
me = request.user
others = User.objects.exclude(id=me.pk)
users_list = itertools.chain([me], others)

Upvotes: 0

kevswanberg
kevswanberg

Reputation: 2109

First, it might be better design to not do this. Have some other endpoint that returns your own user object if you need it, and in the list view treat yourself no differently. But if you really neeed to.

You probably could use an annotation.

User.objects.annotate(is_me=Case(
            When(pk=request.user.pk, then=Value(True)), 
            When(pk__ne=request.user.pk, then=Value(False)),
         output_field=BooleanField())
 ).order_by('-is_me')

Upvotes: 3

Related Questions