I have two Django models, roughly summarized by:
class Thing(Model):
date_created = DateTimeField()
class ThingDateOverride(Model):
thing = ForeignKey(Thing)
category = ForeignKey(Category)
override = DateTimeField()
What I want to do is produce a list of Things for a given a Category sorted by the appropriate ThingDateOverride override field, or the Thing‘s date_created if no such override exists.
In other words:
-
For each
Thingin theQuerySet, keep eitherThing.date_createdor theoverrideif an appropriateThingDateOverrideexists for thatThing/Categorypair. -
Order the
Thingset by the resulting timestamp.
I can pull this off in SQL, but I’d rather avoid writing possibly engine-specific code. I’m currently implementing the logic around the ORM (in pure python), but I would like the database to handle this.
How can I do it?
Is it ok, that category is stored in
ThingDateOverride? If yes, thenThingobject doesn’t have category without override object.I assumed that
ThingDateOverrideobject exists for everyThingobject (so category is assigned to everyThingobject).overridefield can be NULL, thendate_createdobject will be used to sort things. Then this code should sort byoverrideif it exists, or bydate_createdif doesn’t:The idea is to use
extraand selectoverridefield if it exists, ordate_createdif doesn’t as another column, and then sort by that column.Note: this code works only because
overrideanddate_createdfields have different names, so they could be distinguished. Otherwise MySQL will return error, something like “field name is ambiguous”, and need to add table names.