order_by on the basis of time difference (updated_at - created_at)

370 views
Skip to first unread message

Aadil Rashid

unread,
Jan 20, 2022, 11:55:13 PM1/20/22
to django...@googlegroups.com
class ExampleModel(models.Model):
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)



I want to query on UserModel such that the Query set which I get should be orderable in terms of time difference of updated_at - created_at,
I tried
ExampleModel.objects.all().order_by('updated_at' - 'created_at')
but this is not working
it throws, TypeError: unsupported operand type(s) for -: 'str' and 'str'


Django Family Please Help...................

Lalit Suthar

unread,
Jan 21, 2022, 6:33:27 AM1/21/22
to django...@googlegroups.com
won't be possible like this, It will be easy if you have another entry in models which stores the difference between updated and created.
You can update that field whenever an object is updated. And then can run order_by on that field directly


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAYXZx8sABKuJn5Q1ATeHnYsrixfU9wTH_TtPYoR5%3DeAd8DOzA%40mail.gmail.com.

Aadil Rashid

unread,
Jan 21, 2022, 7:11:03 AM1/21/22
to django...@googlegroups.com
This is nice idea, but I can't change the model, as discussed by teammates, i need to figure out any other way to do it on the go.


Feroz Ahmed

unread,
Jan 21, 2022, 8:24:05 AM1/21/22
to Django users
Hi,
in VIEWS
def example=(request):
       fm=ExampleModel.object.created_at
     ExMd=ExampleModel.objects.filter(created_at__lt={'fm'})... ordering conditions.....

Gabriel Araya Garcia

unread,
Jan 21, 2022, 8:54:42 AM1/21/22
to django...@googlegroups.com
Try this:
ExampleModel.objects.all().order_by('updated_at' , '-created_at')
Gabriel Araya Garcia
GMI - Desarrollo de Sistemas Informáticos




--

Fabio C. Barrionuevo da Luz

unread,
Jan 21, 2022, 10:34:52 AM1/21/22
to django...@googlegroups.com
this can be easily solved by using an annotation to calculate the difference and store it in a new temporary column, and then sort by it


from django.db.models import F
from myapp.models import ExampleModel

queryset = ExampleModel.objects.annotate(
    dt_difference=F('updated_at') - F('created_at')
).order_by('dt_difference')

for example in queryset[:10]:
    print(f'created_at={example.created_at} - updated_at={example.updated_at} - dt_difference={example.dt_difference}')





--
Fábio C. Barrionuevo da Luz
Palmas - Tocantins - Brasil - América do Sul


Blog colaborativo sobre Python e tecnologias Relacionadas, mantido totalmente no https://github.com/pythonclub/pythonclub.github.io .

Todos são livres para publicar. É só fazer fork, escrever sua postagem e mandar o pull-request. Leia mais sobre como publicar em README.md e contributing.md.
Regra básica de postagem:
"Você" acha interessante? É útil para "você"? Pode ser utilizado com Python ou é útil para quem usa Python? Está esperando o que? Publica logo, que estou louco para ler...

Lalit Suthar

unread,
Jan 22, 2022, 2:20:45 AM1/22/22
to django...@googlegroups.com

Fabio C. Barrionuevo da Luz's answer will work like a charm!




DJANGO DEVELOPER

unread,
Jan 23, 2022, 1:47:54 AM1/23/22
to Django users
you can use datetime.datetime.strptime to avoid this error. I resolved it few days back.
for this you have to import datetime like this: import datetime

Aadil Rashid

unread,
Jan 23, 2022, 9:09:22 AM1/23/22
to django...@googlegroups.com

Thank you very much Django family for your positive response, and especially to @Fabio C. Barrionuevo da Luz, 
Adding another field to the QuerySet using the "annotate"  function really helped and solves the problem like a charm! as side by @Lalit Suthar

Thank you once again everyone for sharing valuable information here; 
I learned a lot from your sujjections.


Reply all
Reply to author
Forward
0 new messages