0

I use Django with Postgres as my database.

If I run this code:

SomeClass.objects.filter(text__regex=rf"searchkeyword")
the_query = str(SomeClass.query)

The the_query variable will be this:

SELECT * FROM "SomeClass" WHERE "SomeClass "."text"::text ~ searchkeyword

But when you run this query using SomeClass.objects.raw(query), it will show this error:

Exception Value:    
column "usa" does not exist
... WHERE "SomeClass"."text"::text ~* searchkeyword

So, basically, Django ORM can't run the raw query that it made itself.

Does anyone have any thoughts on this?

First Edit: Even for simpler queries like this, I get the same error:

SomeClass.objects.filter(text="searchkeyword")

column "searchkeyword" does not exist
LINE 1: SELECT * FROM SomeClass WHERE text = searchkeyword

Second Edit: This is a little different question than this: Printing Django QuerySet SQL with ""

In my case, even it does not work if double quotations are used and not removed.

Mehrdad Salimi
  • 1,400
  • 4
  • 16
  • 31
  • 2
    Note that `.query` is not really part of the public API, you shouldn't really be using it except for pickling / unpickling queries as described in the documentation – Abdul Aziz Barkat Jan 16 '23 at 16:07
  • It looks like your model is not in sync with the database, so you forgot to make migrations and migrate... – Willem Van Onsem Jan 16 '23 at 16:17
  • @AbdulAzizBarkat that question and it's answers and your second comment here helped me to get some good insight about the root cause of this problem. But, still I am not sure how to solve this problem. If I am not supposed to use `.query` to get the raw query, how should I do it? My scenario: on first page, people can search for a text and I show the result in the second page. In second page, I have a download button to let people download the result of query of the previous page. I can't come up with a better solution other than passing this query using a session variable between views. – Mehrdad Salimi Jan 16 '23 at 16:22
  • @WillemVanOnsem I checked it. There is no migration issue and it is up to date. – Mehrdad Salimi Jan 16 '23 at 16:23
  • @MehrdadSalimi see: [How to print sql query from Django as Debug is False](https://stackoverflow.com/questions/67683964/how-to-print-sql-query-from-django-as-debug-is-false) – Abdul Aziz Barkat Jan 16 '23 at 16:27

0 Answers0