#25212 closed Cleanup/optimization (fixed)
Document RawSQL expression
Reported by: | Tim Graham | Owned by: | Tim Graham |
---|---|---|---|
Component: | Documentation | Version: | 1.8 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
from Anssi on django-developers:
There doesn't seem to be direct documentation about RawSQL expression. The RawSQL is once mentioned in the documentation, but it definitely needs a bit more in the database functions documentation.
The usage of RawSQL is really simple:qs.annotate(val=RawSQL("(select col from sometable where othercol= %s)", (someparam,)))
This is equivalent toqs.extra(select={'val': "select col from sometable where othercol = %s"}, select_params=(someparam,))
The main benefit of using RawSQL is that you can set output_field if needed. The main downside is that if you refer to some table alias of the qs in the raw sql, then it is possible that Django changes that alias (for example, when the qs is used as a subquery in yet another query).
Combining raw SQL with alias relabeling support is possible, too with the following library: https://github.com/akaariai/django-refsql
PR