Friday, May 27, 2016

Nested selects in django queries

Hi everyone!

How can I do nested SELECTs in django queries, like in the following SQL?

SELECT anon_1.timestamp AS anon_1_timestamp, max(anon_1.users) AS users, max(anon_1.servers) AS servers
FROM
(
 SELECT datediff_hours
(:datediff_hours_1, statistics.time) AS timestamp,
   sum
(statistics.users) AS users,
   sum
(statistics.servers) AS servers
 FROM statistics
 WHERE statistics
.gameid = :gameid_1 AND
          datediff_hours
(:datediff_hours_1, statistics.time) >= datediff_hours(:datediff_hours_2, :datediff_hours_3) AND
          datediff_hours
(:datediff_hours_1, statistics.time) <= datediff_hours(:datediff_hours_4, :datediff_hours_5)
 GROUP BY statistics
.time
 
) AS anon_1
GROUP BY anon_1
.timestamp

My model looks like this:

class Statistics(models.Model):
    game_id
= models.IntegerField(db_column='gameid', primary_key=True)
    time
= models.DateTimeField()
    servers
= models.IntegerField()
    users
= models.IntegerField()

`datediff_hours` in SQL is a database function and can be called the following way:

from django.db.models import Func, Value, F

class DateDiffHoursFunc(Func):
     
function = 'datediff_hours'

query
= Statistics.objects.annotate(timestamp=DateDiffHoursFunc(Value(datetime(2016, 5, 26)), F('time')))

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/ae3e2007-e0cc-477e-bbb2-7864f4a9eb91%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment