Opened 2 years ago

Closed 14 months ago

#22973 closed Bug (wontfix)

cannot get SQL code of empty queryset

Reported by: emanuele.paolini@… Owned by: Anderson Resende
Component: Database layer (models, ORM) Version: 1.5
Severity: Normal Keywords:
Cc: Tim Graham 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 (3)

comment:1 Changed 2 years ago by Tim Graham

Cc: Tim Graham added
Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Triage Stage: UnreviewedAccepted
Type: UncategorizedBug

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 21 months ago by Anderson Resende

Owner: changed from nobody to Anderson Resende
Status: newassigned

comment:3 Changed 14 months ago by Tim Graham

Resolution: wontfix
Status: assignedclosed

My understanding is that EmptyResultSet is raised when valid SQL cannot be generated (see #19263 for an example). Therefore I'm going to mark this as "won't fix".

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