Opened 7 years ago

Closed 7 years ago

Last modified 5 years ago

#12079 closed (fixed)

queryset.exists() doesn’t work correctly

Reported by: ramusus Owned by: nobody
Component: Database layer (models, ORM) Version: master
Severity: Keywords:
Cc: ramusus@… Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

I don't understand is it normal?

    In [17]: User.objects.filter(pk=0)
    Out[17]: []

    In [18]: User.objects.filter(pk=0).exists()
    Out[18]: True

The exists() should return False result in this case, I think. This is revision 11653 (Development version)

I have related problem with unique validating of inlineformset and I found that the reason is queryset.exists() doesn't work correctly

Attachments (1)

12079.diff (513 bytes) - added by Karen Tracey 7 years ago.

Download all attachments as: .zip

Change History (11)

comment:1 Changed 7 years ago by ramusus

Cc: ramusus@… added

comment:2 Changed 7 years ago by Alex Gaynor

This works correctly for me.

>>> from django.contrib.auth.models import  User

>>> User.objects.filter(pk=0)
[2] []

>>> User.objects.filter(pk=0).exists()
[3] False

Can you provide some more information about your setup, such as db backend?

comment:3 Changed 7 years ago by Karen Tracey

Triage Stage: UnreviewedAccepted

It's failing on MySQL, at least. This code:

http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py#L2381

simply returns result when the connection can use chunked reads. For mysql result is a callable-interator and bool(<callable-interator>) is True.

Changed 7 years ago by Karen Tracey

Attachment: 12079.diff added

comment:4 Changed 7 years ago by Karen Tracey

I've attached a possible patch but I don't have much of a clue when it comes to the ORM so someone with more of one in that area should see if there's a better way, etc.

comment:5 Changed 7 years ago by Karen Tracey

(No tests needed for this fix...a lookup test added in r11647 is currently failing on backends where this problem occurs.)

comment:6 Changed 7 years ago by ramusus

Can you provide some more information about your setup, such as db backend?

DATABASE_ENGINE = 'postgresql_psycopg2'

comment:7 Changed 7 years ago by Alex Gaynor

Karen, that patch looks correct. I didn't notice this as Jacob committed a different version than my patch (which included a call to list()).

comment:8 Changed 7 years ago by Alex Gaynor

Has patch: set
milestone: 1.2
Triage Stage: AcceptedReady for checkin
Version: 1.1SVN

comment:9 Changed 7 years ago by Karen Tracey

Resolution: fixed
Status: newclosed

(In [11654]) Fixed #12079: Changed has_results to get a single result, thus preventing exists() from always returning True on backends that support chunked reads.

comment:10 Changed 5 years ago by Jacob

milestone: 1.2

Milestone 1.2 deleted

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