Query and order by time difference of a specified time.

39 views
Skip to first unread message

ap....@x76.eu

unread,
May 23, 2016, 8:26:13 AM5/23/16
to django...@googlegroups.com
Hi.
I am looking for a way to find a row which is closest to a specified
point in time, no matter if the row is before or after.

In plain SQL (using SQLite as example), it's very easy to do;

SELECT *,
abs(
strftime('%s','2015-05-21 23:05:00') - strftime('%s',`created`)
) AS timdif
FROM myapp_posts f ORDER BY timdif LIMIT 10;


The above snippet converts the specified date and field to epoch
seconds, subtracts them and then sorts the query according to the
difference.

Is it possible do this in Django without resorting to raw queries?

Thank you.

Ketan Bhatt

unread,
May 23, 2016, 10:16:32 AM5/23/16
to Django users
Take a look at the `extra` method of the queryset in Django. It allows you to do what you are trying to do by raw SQL.

https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.extra

Check the above link, the example with `annotate` will be interesting for you.

I think your aim should be to create a new field and then do a `order_by` and `first`.

Fabio C. Barrionuevo da Luz

unread,
May 23, 2016, 10:25:44 AM5/23/16
to django...@googlegroups.com
it would probably be better to use a custom "Func"[1] and a custom "Query Expression" [2] than user QuerySet.extra 





--
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 post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5b556c8b-2012-4bd7-89c5-bddbbdb4c3b9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
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...

Reply all
Reply to author
Forward
0 new messages