models.my_model.objects.get(id=None) returns a result in MySQL
|Reported by:||rpbarlow||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.0|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I stumbled upon an interesting bug today, and I believe that I've narrowed it down to Django's MySQL layer. When using MySQL, models.my_model.objects.get(id=None) will return a result, when it should raise a DoesNotExist exception. Here is a very simple example that will reproduce this error. Suppose you have the following model:
from django.db import models class company(models.Model): name = models.CharField(max_length=255, unique=True) active = models.BooleanField(default=True)
Here is a shell session that exhibits the behavior I expect, using sqlite3:
>>> from mysqltest import models >>> models.company.objects.all()  >>> c = models.company(name='the Company') >>> c.save() >>> models.company.objects.all() [<company: company object>] >>> models.company.objects.get(id=1) <company: company object> >>> models.company.objects.get(id=None) Traceback (most recent call last): File "<console>", line 1, in <module> File "//usr/lib/python2.5/site-packages/django/db/models/manager.py", line 93, in get return self.get_query_set().get(*args, **kwargs) File "//usr/lib/python2.5/site-packages/django/db/models/query.py", line 303, in get % self.model._meta.object_name) DoesNotExist: company matching query does not exist.
And here is a shell session demonstrating the behavior that MySQL exhibits:
>>> from mysqltest import models >>> models.company.objects.all()  >>> c = models.company(name='the Company') >>> c.save() >>> models.company.objects.all() [<company: company object>] >>> models.company.objects.get(id=1) <company: company object> >>> models.company.objects.get(id=None) <company: company object>
I have done a little poking around to narrow down whether the problem is in Python's MySQL bindings, or in Django's MySQL layer, and I do believe it is a Django bug. When I executed the queries (gotten from django.db.connection) directly using python's mysql bindings, the results came back as expected with no results. I also tried using the mysql shell directly, and also found it to return the expected results (nothing).