Opened 9 months ago

Last modified 3 months ago

#22973 assigned Bug

cannot get SQL code of empty queryset

Reported by: emanuele.paolini@… Owned by: andersonresende
Component: Database layer (models, ORM) Version: 1.5
Severity: Normal Keywords:
Cc: timo Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Suppose you have defined any Model class.

The code:

str(Model.objects.filter(id__in=[]).query)

raises an exception:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 174, in __str__
    sql, params = self.sql_with_params()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 182, in sql_with_params
    return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 85, in as_sql
    where, w_params = self.query.where.as_sql(qn=qn, connection=self.connection)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/where.py", line 126, in as_sql
    raise EmptyResultSet
EmptyResultSet

instead this works fine:

str(Model.objects.none().query)

Change History (2)

comment:1 Changed 8 months ago by timo

  • Cc timo added
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted
  • Type changed from Uncategorized to Bug

Note that your second version works on 1.5, but also raises EmptyResultSet starting in 1.6. I don't think this change was intentional, although I think the pattern you presented isn't treated as an official API for retrieving SQL for a queryset and I'm not sure what would be involved in fixing it, so perhaps someone else may close this as "won't fix".

comment:2 Changed 3 months ago by andersonresende

  • Owner changed from nobody to andersonresende
  • Status changed from new to assigned
Note: See TracTickets for help on using tickets.
Back to Top