How to query set as ORDER BY and GROUP BY in django? - python

This my is query:
SELECT kategoriharga,ongkoskirim,diskon,ratingproduk,ratingtoko,label
FROM
(SELECT *
FROM pohonkeputusan
where perdaerah='Kabupaten Toba Samosir'
order by label desc
) AS sub
GROUP BY
kategoriharga,ongkoskirim,diskon,ratingproduk,ratingtoko
How to make to be query set in Django?

I don't understand why you want to group by all fields. Try to use distinct:
Pohonkeputusan.objects.filter(perdaerah='Kabupaten Toba Samosir').order_by('-label').values_list('kategoriharga', 'ongkoskirim', 'diskon', 'ratingproduk', 'ratingtoko').distinct()

Related

Can't convert SQL to django query (having doesn't work)

I have this SQL:
SELECT
stock_id, consignment_id, SUM(qty), SUM(cost)
FROM
warehouse_regсonsignmentproduct
WHERE
product_id = '1'
GROUP BY
stock_id, consignment_id
HAVING
SUM(qty) > 0
I used django ORM to create this query:
regСonsignmentProduct.objects
.filter(product='1')
.order_by('period')
.values('stock', 'consignment')
.annotate(total_qty=Sum('qty'), total_cost=Sum('cost'))
.filter(total_qty__gt=0)
But my django query returns an incorrect result.
I think, the problem is in "annotate"
Thanks!
You need to order by the values to force grouping, so:
regСonsignmentProduct.objects.filter(product='1').values(
'stock', 'consignment'
).annotate(
total_qty=Sum('qty'),
total_cost=Sum('cost')
).order_by('stock', 'consignment').filter(total_qty__gt=0)

How to build Django queries to get list of data that satisfy many conditions?

I am trying to get a list of user_id by executing such sqlite query.
SELECT
u.user_id
FROM
users u
WHERE
u.role_id IN ( 1, 2 )
AND ( SELECT COUNT( * ) FROM purchases p WHERE p.user_id = u.id ) >= 1
AND (
SELECT
tagged.tag_id
FROM
tagged
INNER JOIN ( SELECT polled.answer_id FROM polled WHERE polled.user_id = u.id ) AS a
WHERE
a.answer_id = tagged.answer_id
) IN ( 1,2 )
How can run that sql using django orm? It's so hard to understand logic querysets like this...
Users.objects.annotate(cnt=Count('purchases')).filter(Exists(Polled.objects.filter(user=OuterRef('pk')))).filter(cnt__gt=1).filter(role__in=[1, 2]).values_list('user_id', flat=True)
ForeignKeys Relations Image
Please help to build correct queries to get list of users that satisfy the conditions. Thanks.

How to use extra function to aggregate a table separately django?

How to use extra function to aggregate a table separately django?
I tried the example below, but I did not succeed.
Thank you very much for your attention.
aulas = Aula.objects.extra(
select={
'reposicao': 'SELECT * FROM app_reposicao WHERE app_cfc_reposicao.id = app_aula.id_tipo'
})
subquery must return only one column LINE 1: SELECT (SELECT * FROM
app_reposicao WHERE app_reposi...

Django: get duplicates based on annotation

I want to get all duplicates based on a case insensitive field value.
Basically to rewrite this SQL query
SELECT count(*), lower(name)
FROM manufacturer
GROUP BY lower(name)
HAVING count(*) > 1;
with Django ORM. I was hoping something like this would do the trick
from django.db.models import Count
from django.db.models.functions import Lower
from myapp.models import Manufacturer
qs = Manufacturer.objects.annotate(
name_lower=Lower('name'),
cnt=Count('name_lower')
).filter('cnt__gt'=1)
but of course it didn't work.
Any idea how to do this?
you can try it:
qs = Manufacturer.objects.annotate(lname=Lower('name')
).values('lname').annotate(cnt=Count(Lower('name'))
).values('lname', 'cnt').filter(cnt__gt=1).order_by('lname', 'cnt')
why should add the order_by ordering-or-order-by:
the sql query looks like:
SELECT
LOWER("products_manufacturer"."name") AS "lname",
COUNT(LOWER("products_manufacturer"."name")) AS "cnt"
FROM "products_manufacturer"
GROUP BY LOWER("products_manufacturer"."name")
HAVING COUNT(LOWER("products_manufacturer"."name")) > 1
ORDER BY "lname" ASC, "cnt" ASC

SQLAlchemy select from subquery and order by subquery field

I have a database table with tweets in a jsonb field.
I have a query to get the tweets ordered by the most retweeted, this is what it looks like:
SELECT * FROM (
SELECT DISTINCT ON (raw->'retweeted_status'->'id_str')
raw->'retweeted_status' as status,
raw->'retweeted_status'->'retweet_count' as cnt
FROM tweet
WHERE (raw->'retweeted_status') is not null
ORDER BY raw->'retweeted_status'->'id_str', cnt DESC
) t
ORDER BY cnt DESC
I'm trying to create this query with sqlalchemy, this is where i got so far:
session.query(Tweet.raw['retweeted_status'],
Tweet.raw['retweeted_status']['retweet_count'].label('cnt'))\
.filter(~Tweet.raw.has_key('retweeted_status'))\
.distinct(Tweet.raw['retweeted_status']['id_str']).order_by(Tweet.raw['retweeted_status']['id_str'].desc()).subquery()
But how to go from that to order by cnt?
It may not produce the exact query you have shown but should point you in the right direction: you can use your label 'cnt' in order_by, like: .order_by('cnt').
Moreover you can use your label as an argument for sqlalchemy.desc function. Summing up:
from sqlalchemy import desc
q = (
session.query(
Tweet.raw['retweeted_status'],
Tweet.raw['retweeted_status']['retweet_count'].label('cnt')
)
.filter(~Tweet.raw.has_key('retweeted_status'))
.distinct(
Tweet.raw['retweeted_status']['id_str']
)
.order_by(desc('cnt'))
).subquery()
Additional hint: you can format your query nicely if you put it in parentheses.
You may want to read answers to a general question on python sqlalchemy label usage too.

Categories

Resources