Opened 5 years ago
Last modified 2 years ago
#30655 closed Bug
len(queryset) and queryset.count() return different results — at Initial Version
Reported by: | Sander Kleijwegt | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
According to the queryset.count() documentation "you should always use count() rather than loading all of the record into Python objects and calling len() on the result" (see here), which seems to imply that the results of both functions should always be identical. Here is a simple example that shows the contrary.
Models:
class Bar(models.Model): pass class Foo(models.Model): fooint = models.IntegerField() foobar = models.ForeignKey(Bar, related_name='foos', on_delete=models.CASCADE)
Shell Output:
>>> import django >>> django.__version__ '2.0.4' >>> from foobar.models import Foo, Bar >>> bar = Bar.objects.create() >>> foo1 = Foo.objects.create(fooint=1, foobar=bar) >>> foo2 = Foo.objects.create(fooint=2, foobar=bar) >>> Bar.objects.all().order_by('foos__fooint').count() 1 >>> len(Bar.objects.all().order_by('foos__fooint')) 2 >>> Bar.objects.all().order_by('foos__fooint') <QuerySet [<Bar: Bar object (1)>, <Bar: Bar object (1)>]>
Note:
See TracTickets
for help on using tickets.