I sometimes considered issuing Django raw queries.
For example, when you want to use the result calculated based on the column instead of specifying the column in SELECT or WHERE.
I was in trouble like this.
--There is no query builder! ――It looks like it's in a plugin! ――But does PostgreSQL support it? → I'm using MySQL!
Ah, the ORM object has a raw method ... well,
entities = Entity.objects.raw("SELECT concat_ws(',', id, name) AS mystr FROM entities WHERE name IN %s", params=(list(names),))
Is it okay? But the list specified in IN does not pass. Hmm,
https://docs.djangoproject.com/ja/1.9/ref/models/expressions/#raw-sql-expressions
But it doesn't work ...
So, when I searched a little more, I found something like this.
https://docs.djangoproject.com/ja/1.9/ref/models/querysets/#django.db.models.query.QuerySet.extra
With this,
entities = Entity.objects.extra(
select={'mystr': "concat_ws(',', id, name)"},
where=['name IN %s'],
params=[list(names)]
)
It feels like I can write a little better than raw.
However ...!
Use this method as a last resort
This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods.
Because there is, it may be better not to use it ...
https://docs.djangoproject.com/ja/1.9/ref/models/expressions/#raw-sql-expressions
Looks better to use
Recommended Posts