I’ve got a model eg. Car with a foreign key eg. Owner, which may or may not be blank.
The Car has a creation_date.
I would like to order these cars by date, but if the car has an owner, the date of birth of the owner must be taken instead of the creation_date of the car.
Is this possible?
Have a look at this similar question: Good ways to sort a queryset? – Django
You can’t use the model’s Meta
orderingas it only accepts one fieldhttps://docs.djangoproject.com/en/dev/ref/models/options/#ordering
You can’t use the query
order_by('creation_date', 'birthdate')as it only sorts by birthdate if they have the samecreation_dateSo, you could write a custom manager to do incorporate a custom sort for you.
so now you can query:
to get all a queryset of sorted car’s