How rewrite query in Django ORM?

32 views
Skip to first unread message

Николай Инкогнито

unread,
Aug 24, 2017, 4:44:40 PM8/24/17
to Django users
SELECT * FROM T WHERE REPLACE(T.field, '-', ' ') = REPLACE(VALUE,'-', ' ')

wang sheng

unread,
Aug 24, 2017, 10:25:33 PM8/24/17
to django...@googlegroups.com
why you need rewrite query in ORM 

you can use "raw query" in django 


2017-08-25 4:25 GMT+08:00 Николай Инкогнито <mmm...@gmail.com>:
SELECT * FROM T WHERE REPLACE(T.field, '-', ' ') = REPLACE(VALUE,'-', ' ')

--
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/c0f10848-ac43-43ad-87a5-1a24e902cbe9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Daniel Hepper

unread,
Aug 25, 2017, 11:01:07 AM8/25/17
to Django users
You have to assign the left side of the comparison to a field name with annotate. At least I'm not aware of another way, except falling back to raw SQL.

Assuming VALUE in your example is just a variable:

T.objects.annotate(field_replaced=F('field'), Value('-'), Value(' '), function='replace')).filter(field_replaced=Func(Value('my_value'), Value('-'), Value(' '), function='replace'))

This results in a query like this:

SELECT "T"."id", "T"."field", replace("T"."field", '-', ' ') AS "field_replaced" FROM "T" WHERE replace("T"."field", '-', ' ') = (replace('my_value', '-', ' '))

Hope that helps!

Daniel
Reply all
Reply to author
Forward
0 new messages