combining ORM and raw SQL in same query

70 views
Skip to first unread message

Larry Martell

unread,
Feb 20, 2017, 10:50:44 AM2/20/17
to django...@googlegroups.com
Is there any way to use both the ORM and raw SQL in the same query?

I have an existing app that uses the ORM and now I have a need to add
SQL like this to the select:

(CASE
WHEN TRIM(IFNULL(roiname, '')) IN ('', 'None') THEN CONCAT_WS('.',
roi_type_id, roi_id)
WHEN CONCAT_WS('.', roi_type_id, roi_id) = roiname THEN roiname
ELSE CONCAT_WS('.', roi_type_id, roi_id, roiname)
END) as roiname

and SQL like this to the where:

AND (CASE
WHEN TRIM(IFNULL(roiname, '')) IN ('', 'None') THEN CONCAT_WS('.',
roi_type_id, roi_id)
WHEN CONCAT_WS('.', roi_type_id, roi_id) = roiname THEN roiname
ELSE CONCAT_WS('.', roi_type_id, roi_id, roiname)
END) REGEXP 'foo'

As far as I know I cannot do anything like that with the ORM. I don't
want to have to rewrite everything with raw SQL. Is there a way to mix
them?

m1chael

unread,
Feb 20, 2017, 10:52:46 AM2/20/17
to django...@googlegroups.com
i did something like this recently using .extra / select





--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACwCsY46a1-A6zqfZVeUC5r%2B-xrupii_DJOVJRb%2B5K-Z22ZgGQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Larry Martell

unread,
Feb 20, 2017, 4:01:05 PM2/20/17
to django...@googlegroups.com
Thanks!

Matthew Pava

unread,
Feb 21, 2017, 9:25:34 AM2/21/17
to django...@googlegroups.com
I would use Case and When and other Func objects.
https://docs.djangoproject.com/en/1.10/ref/models/conditional-expressions/
That way we don't have to depend on raw SQL.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACwCsY7xjBPYK17Vp2H-uV2c0aH3p-%2BG_Ya5n9dBjifE0Nk6ag%40mail.gmail.com.

Larry Martell

unread,
Feb 21, 2017, 9:31:00 AM2/21/17
to django...@googlegroups.com
Thanks. I did not know about those.
Reply all
Reply to author
Forward
0 new messages