exists() is returning wrong answers when I'm filtering on the results of Count(). Maybe I wanted to know whether any blog post had gotten over 100 comments. The following transcripts are on Django 1.8.1 / Python 2.7.9 / SQLite. The answer is also wrong on Python 3.4.3 but correct on Django 1.7.4.
Testcase (see below for setup)
Assume at least 2 Users exist in the database.
>>> User.objects.annotate(c=models.Count('id')).values_list('c')
[(1,), (1,)]
>>> User.objects.annotate(c=models.Count('id')).filter(c__gt=1)
[]
So far this is to be expected. No user has more than one id--which makes the following surprising.
>>> User.objects.annotate(c=models.Count('id')).filter(c__gt=1).exists()
True
What further raises the suspicion of unintended behavior is that if you increase the "1" to the number of Users (or higher), then the exists() starts to return False.
>>> User.objects.annotate(c=models.Count('id')).filter(c__gt=User.objects.count()).exists()
False
Setup
$ django-admin2 startproject blah
$ cd blah
$ ./manage.py syncdb
...
You have installed Django's auth system, and don't have any superusers defined.
Would you like to create one now? (yes/no): no
$ ./manage.py shell
>>> from django.contrib.auth.models import User
>>> User.objects.create(username='a')
>>> User.objects.create(username='b')
>>> from django.db import models
Bisected regression to 0c7633178fa9410f102e4708cef979b873bccb76. Test for Django's test suite attached.