#9041: invalid count result when paired with select_related
------------------------------------------------------------+---------------
Reporter: Mathieu Bouchard <[email protected]> | Owner:
nobody
Status: new | Milestone:
1.1
Component: Database layer (models, ORM) | Version:
1.0
Resolution: | Keywords:
Stage: Accepted | Has_patch: 0
Needs_docs: 0 | Needs_tests: 0
Needs_better_patch: 0 |
------------------------------------------------------------+---------------
Comment (by mbouchar):
As I said in my first message, this happens only when the data in the db
is not valid for django (when integrating legacy data, for example, or
when the django model has changed). For example, if we have the following
model
{{{
from django.db import models
class ForeignModel(models.Model):
pass
class Key(models.Model):
value = models.CharField(blank = False, max_length = 12)
foreignmodel = models.ForeignKey(ForeignModel, blank = True, null =
True)
class Session(models.Model):
key = models.ForeignKey(Key)
}}}
If we add some data (and some where the foreignmodel value is null), and
we then change the foreignmodel field to require a value, this triggers
the bug:
{{{
foreignmodel = models.ForeignKey(ForeignModel)
}}}
Of course, the data is then invalid and the database does not reflect the
django model. The QuerySet count() method is using "select count(field)"
for obvious speed reasons, but do not seem to perform the select_related.
For example, the current implementation of:
{{{
>>> Session.objects.filter(key__value = "1").select_related().count()
15
}}}
Seems to be translated to the following SQL code:
{{{
> SELECT COUNT(S.id) FROM example_session S, example_key K WHERE S.key_id
= K.id AND K.value = "1";
15
}}}
It should probably be modified to the following SQL code:
{{{
> SELECT COUNT(S.id) FROM example_session S, example_key K,
example_foreignmodel F WHERE S.key_id = K.id AND K.foreignmodel_id = F.id
AND K.value = "1";
7
}}}
This would return the same data as the following django code:
{{{
>>> len(Session.objects.filter(key__value = "1").select_related())
7
}}}
--
Ticket URL: <http://code.djangoproject.com/ticket/9041#comment:5>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en
-~----------~----~----~----~------~----~------~--~---