row_1(PK) | row_2 | row_3 |
---|---|---|
1 | row | one |
2 | row | two |
3 | row | three |
Data from my database table looks like the above table.
SELECT
GROUP_CONCAT(row_3)
FROM table_
WHERE row_2 = 'row'
GROUP BY row_2;
My Django query to achieve above mysql query
table_.objects.filter(
row_2='row'
).annotate(
val=GroupConcat('row_3', '')
).values('val')
When converting the above ORM to raw mysql query, it's grouing by primary key (row_1). I want to group by 'row_2' column .
You need to use .order_by(…)
[Django-doc], yes I know that sounds strange, so:
table_.objects.filter(row2='row').values('row2').annotate(
val=GroupConcat('row3', '')
).order_by('row2')
But here it looks like you are actually making an aggregate, since only one sort of value for row2
is picked due to the filtering, so grouping by that value is not necessary. You can use .aggregate(…)
[Django-doc] in that case:
table_.objects.filter(row2='row').aggregate(val=GroupConcat('row3', ''))