[Answered ]-Django — order model records based on criteria?


You can create a custom manager, which will do what you want.

class CompanyFilter(models.Manager):
   def get_query_set(self):
        qs = super(CompanyFilter, self).get_query_set()
        return qs.filter(is_company=True).order_by('company_name')

class PersonFilter(models.Manager):
   def get_query_set(self):
        qs = super(PersonFilter, self).get_query_set()
        return qs.filter(is_company=False).order_by('last_name')

class Contact(models.Model):
   # ... your regular fields

   companies = CompanyFilter()
   people = PersonFilter()

all_companies = Contact.companies.all()
all_people = Contact.people.all()
all_contacts = Contact.objects.all()


1 . assuming that either of the fields is always NULL you can use extra query:

    .extra(select=dict(name='coalesce(last_name, company_name)'))

(COALESCE seems to be supported in all major database engines)

2 . or simply eliminate either last_name or company_name and put last names and company names in to the same field and sort by it.


Leave a comment