0

I have the following Django class:

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

def make_id():
    '''
    inspired by http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram
    '''
    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/manager.py", 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/query.py", line 334, in get
    self.model._meta.object_name
DoesNotExist: My_Class matching query does not exist.

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

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272
  • Possible duplicate of [matching query does not exist Error in Django](http://stackoverflow.com/questions/5508888/matching-query-does-not-exist-error-in-django) – Saqib Ali Sep 02 '16 at 17:37

1 Answers1

2

It could be you have no My_Class with id = 5000

try:
    mc = My_Class.objects.get(pk=id)
except My_Class.DoesNotExist:
    mc = None
sr3z
  • 400
  • 1
  • 2
  • 10
  • So let me get this straight... the search operation failed with an error message that clearly says "that object does not exist", and his first instinct was to run to the forums instead of finding another way to verify that the object actually exists?! – John Gordon Sep 02 '16 at 17:43
  • To be clear the error message is " matching query does not exist." which could be confusing. When I saw such message for the first time I just googled that. The question is how to avoid such issues programmatically – sr3z Sep 02 '16 at 17:45
  • No, it says that the class matching the query does not exist. Pretty clear. – Michael Josephson Sep 02 '16 at 18:49