Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Sort model based on difference between two of its fields

Take a simple class like this.

class MyModel(models.Model):
    last_updated = models.DateTimeField(auto_now_add=True)
    last_viewed  = models.DateTimeField(auto_now_add=True)

All I want to do is sort the output of a query on this model by the time between those two fields so that things that haven't been viewed since they were updated show higher up than things that have.

I feel like I should be able to annotate the table and sort on that annotation, but I'm no genius when it comes to annotations (or raw SQL, for that matter). Could somebody kick me in the right direction?

like image 291
Oli Avatar asked May 27 '11 16:05

Oli


1 Answers

You can do something like this:

MyModel.objects.extra(select={'offset': 'last_viewed - last_updated'}).order_by('offset')

See the docs for a detailed explanation.

like image 193
Sam Dolan Avatar answered Nov 15 '22 22:11

Sam Dolan