[Answer]-Subquery in select Django

1👍

You can see the raw sql behind your queries using the query attribute of Queryset.

For example, look at the sql behind my first answer using select_related, it’s clear the generated sql doesn’t behave as expected and accessing the long_url will result in additional queries.

Take 2

You can follow relationships using double underscore notation like this

qs = Stats_links_ads.objects
        .values('link_id', 'link_id__long_url')
        .annotate(Sum('views'), Sum('clicks'))
str(qs.query)
'SELECT 
    "stackoverflow_stats_links_ads"."link_id_id", 
    "stackoverflow_link"."long_url", 
    SUM("stackoverflow_stats_links_ads"."clicks") AS "clicks__sum",
    SUM("stackoverflow_stats_links_ads"."views") AS "views__sum"
FROM "stackoverflow_stats_links_ads" 
    INNER JOIN "stackoverflow_link" 
    ON ("stackoverflow_stats_links_ads"."link_id_id" = "stackoverflow_link"."short_key")
GROUP BY 
    "stackoverflow_stats_links_ads"."link_id_id", 
    "stackoverflow_link"."long_url"'

I’m not working with any data, so I haven’t verified it, but the sql looks right.

Take 1

Does not work

Can’t you use .select_related? [docs]

qs = Stats_links_Ads.objects.select_related('link')
     .values('link_id').annotate(Sum('views'), Sum('clicks'))
str(qs.query)
'SELECT 
    "stackoverflow_stats_links_ads"."link_id_id", 
    SUM("stackoverflow_stats_links_ads"."clicks") AS "clicks__sum", 
    SUM("stackoverflow_stats_links_ads"."views") AS "views__sum" 
FROM "stackoverflow_stats_links_ads" 
GROUP BY "stackoverflow_stats_links_ads"."link_id_id"'
👤Enrico

Leave a comment