當我做「object_name.objects.get(id = 1)」我得到錯誤。此前,當id = 1時,我得到了這個錯誤,但是當id = 2時它返回了對象。然後我刪除了我所做的所有條目,希望它會從id = 1開始,但現在它會發生錯誤。DoesNotExist:對象匹配查詢不存在
有人可以解釋爲什麼會發生這種情況,我該怎麼辦?
>>> from course.models import Course, Content
>>> Course.objects.get(id=1)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/vagrant/edu-venv/local/lib/python2.7/site-packages/django/db/models /manager.py", line 143, in get
return self.get_query_set().get(*args, **kwargs)
File "/home/vagrant/edu-venv/local/lib/python2.7/site-packages/django/db/models /query.py", line 389, in get
(self.model._meta.object_name, kwargs))
DoesNotExist: Course matching query does not exist. Lookup parameters were {'id': 1}
此外object_name.object.all()給所有我已經進入
>>> Course.objects.all()
[<Course: JAVA>, <Course: HTML5>]
這很自然,你必須做的是應用'try'和'except',該函數處理那個問題 – catherine
請閱讀:https://docs.djangoproject.com/en/dev/topics/db/queries/ #檢索單個對象並得到 –
在shell中執行此操作:'Course.objects.values_list('pk',flat = True)',並查看爲兩個對象生成的ID。你會知道爲什麼'id = 1'失敗 – karthikr