Saqib Ali Saqib Ali - 8 months ago 30
Python Question

Why does this very basic query on this Django model fail?

I have the following Django class:

from caching.base import CachingManager, CachingMixin
from mptt.models import MPTTModel

def make_id():
inspired by
START_TIME = 1876545318034
return (int(time.time()*1000) - START_TIME << 23 ) | random.SystemRandom().getrandbits(23)

class My_Class(CachingMixin, MPTTModel):
id = models.BigIntegerField(default=make_id, primary_key=True)
# Other Attributes Snipped here for brevity

But look what happens when I try to query this class:

>>> My_Class.objects.get(pk=5000)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "my_virtual_env/lib/python2.7/site-packages/django/db/models/", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "my_virtual_env/lib/python2.7/site-packages/django/db/models/", line 334, in get
DoesNotExist: My_Class matching query does not exist.

Why does it fail?? How can I fix this?


It could be you have no My_Class with id = 5000

    mc = My_Class.objects.get(pk=id)
except My_Class.DoesNotExist:
    mc = None