Home > Enterprise >  Ordering queryset by model string
Ordering queryset by model string

Time:03-06

I'm defining the string for a model as follows:

class Customer(models.Model):

    company_name = ...
    first_name = ...
    last_name = ...

    def __str__(self):

        if self.company_name != None and self.company_name != "":
            return self.company_name
        else:
            return self.first_name   " "   self.last_name
    

When querying for customers, is it possible to order the query by the string that represents the model instance?

eg c = Customers.objects.all().order_by('???????')

Thanks!

CodePudding user response:

You can use annotations to generate the same string as your __str__ method in a queryset, you can then order by that annotation.

Concat can be used to join first_name and last_name into a single field

Coalesce will return the first non-null value, this can be used to implement your if/else

from django.db.models import Value
from django.db.models.functions import Coalesce, Concat

Customer.objects.annotate(
    full_name=Concat('first_name', Value(' '), 'last_name')
).annotate(
    display_str=Coalesce('company_name', 'full_name')
).order_by('display_str')
  • Related