简体   繁体   中英

Django Max of related entity

In SQL prompt when I try this:

select app_name, max(SNAP_SNAPINFO.id)
from SNAP_SNAPTOPO inner JOIN SNAP_SNAPINFO ON SNAP_SNAPTOPO.SNP_ID = SNAP_SNAPINFO.ID
where app_name in ('invoiceserv','cal_host') and stream = 'live' and  snp_id <= 135353 
group by app_name;

I get this:

cal_host    126972
invoiceserv 127240

In django I am not able to program to the same requirement

>>> st = SnapTopo.objects.filter(app_name__in=['invoiceserv','cal_host'],
...                         snp__stream='live',
...                         snp__id__lte=125353).values('app_name', 'snp__id').\
...                         annotate(snpid=Max('snp__id'))
>>> print st.query
SELECT "SNAP_SNAPTOPO"."APP_NAME", "SNAP_SNAPTOPO"."SNP_ID", MAX("SNAP_SNAPTOPO"."SNP_ID") AS "SNPID" FROM "SNAP_SNAPTOPO" LEFT OUTER JOIN "SNAP_SNAPINFO" ON ("SNAP_SNAPTOPO"."SNP_ID" = "SNAP_SNAPINFO"."ID") WHERE ("SNAP_SNAPINFO"."STREAM" = live  AND "SNAP_SNAPTOPO"."APP_NAME" IN (invoiceserv, cal_host) AND "SNAP_SNAPTOPO"."SNP_ID" <= 125353 ) GROUP BY "SNAP_SNAPTOPO"."APP_NAME", "SNAP_SNAPTOPO"."SNP_ID", "SNAP_SNAPTOPO"."APP_NAME", "SNAP_SNAPTOPO"."SNP_ID", "SNAP_SNAPINFO"."SNP_TS", "SNAP_SNAPINFO"."SNP_NUMBER" ORDER BY "SNAP_SNAPINFO"."SNP_TS" ASC, "SNAP_SNAPINFO"."SNP_NUMBER" DESC
>>> print st
[{'snpid': 72538, 'app_name': u'cal_host', 'snp__id': 72538}, {'snpid': 74723, 'app_name': u'invoiceserv', 'snp__id': 74723}, {'snpid': 89231, 'app_name': u'cal_host', 'snp__id': 89231}, {'snpid': 91960, 'app_name': u'cal_host', 'snp__id': 91960}, {'snpid': 96325, 'app_name': u'invoiceserv', 'snp__id': 96325}, {'snpid': 100656, 'app_name': u'cal_host', 'snp__id': 100656}, {'snpid': 104496, 'app_name': u'invoiceserv', 'snp__id': 104496}, {'snpid': 106982, 'app_name': u'cal_host', 'snp__id': 106982}, {'snpid': 120957, 'app_name': u'cal_host', 'snp__id': 120957}]

I want to have a django code which emulates the earlier mentioned SQL statement's behavior. What am I missing?

As of now, I am doing the below:

>>> for appname in ('invoiceserv', 'cal_host'):
...     max_snp_id = SnapTopo.objects.filter(app_name=appname, snp__stream='live',
...                             snp__id__lte=125353).aggregate(Max('snp__id'))
...     print appname, max_snp_id
...
invoiceserv {'snp__id__max': 104496}
cal_host {'snp__id__max': 120957}

I am looking for an optimal solution using django APIs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM