Backpatch of 5e1f4656 from master. Conflicts: django/db/models/sql/query.py tests/queries/models.py tests/queries/tests.py