为什么这个Django模型的这个非常基本的查询失败了?

时间:2016-09-02 17:18:04

标签: python django django-queryset

我有以下Django类:

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

但是看看当我尝试查询这个类时会发生什么:

>>> 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.

为什么会失败?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

可能你没有id = 5000的My_Class

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