When I build a model in Django, I add the following information:
def __unicode__(self):
return self.some_field
class Meta:
ordering = ['some_field_to_order_by']
Is it possible to set ordering based on a sort of if/else scenario?
For example, I have a customer model which, for sake of argument, has these fields:
first_name
last_name
company_name
is_company (boolean)
If the customer is a Company, I only add information to the company_name field and set is_company=True, leaving the other two blank. If the customer is a person, then I add information to the first_name and last_name fields, leaving the company_name blank and the is_company=False.
I want to sort these records by last_name if the is_company field is False and company_name if is_company is True.
Is this possible?
EDIT For an example (per request, sort of)
For my app, this customer table holds information regarding owners of security systems. Sometimes, a security system is installed in a residential setting. In this case, the owner of the system is a person — thus, I would enter the first_name and last_name into the customer record. Sometimes the system is installed in a commercial setting, therefore the owner is a company. For this I enter only the company_name field, leaving the other fields blank.
Now, when I provide an estimate for a NEW security system installation, I can provide the estimate to a new customer or an existing customer (existing customer, but a new location for them). When it is an existing customer, I have a drop down box that lists all existing customers (ALL RECORDS in the customer table).
THIS is where I want all the records to be ordered properly. As it is now, I get a jumbled mess of hundreds of records making it brutal to find the existing owner.
Hopefully this helps with what I’m trying to achieve.
You can create a custom manager, which will do what you want.