Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#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 to qs.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

Change History (3)

comment:1 by Tim Graham, 9 years ago

Has patch: set

comment:2 by Tim Graham <timograham@…>, 9 years ago

Resolution: fixed
Status: newclosed

In 97fa7fe:

Fixed #25212 -- Documented the RawSQL expression.

comment:3 by Tim Graham <timograham@…>, 9 years ago

In 6f6043fd:

[1.8.x] Fixed #25212 -- Documented the RawSQL expression.

Backport of 97fa7fe961f961b6c93a11b50a7a1ed35c8bce8d from master

Note: See TracTickets for help on using tickets.
Back to Top