'sort django queryset using a temporary field which is not listed in model

My model is as follows:

class People(models.Model):
    name = models.charfield(max_length = 200)
    surname = models.charfield(max_length = 200)

In my function:

people_list = People.objects.all()
for each in people_list:
    if some_conditions:
        each.level = 1
    else:
        each.level = 2

I need to sort the people_list using level variable I've added. I get FieldError when trying to do

people_list = people_list.order_by('level')


Solution 1:[1]

You can annotate the extra field with conditional value and order using that field. Here's an example.

People.objects.annotate(level=Case(When(condition,then=Value(1)),default=Value(2),output_field=IntegerField())).order_by('level')

Doc related to When Case, https://docs.djangoproject.com/en/4.0/ref/models/conditional-expressions/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashin Shakya