欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在Python的Django框架中獲取單個對象數(shù)據(jù)的簡單方法

 更新時間:2015年07月17日 11:14:08   投稿:goldensun  
這篇文章主要介紹了在Python的Django框架中獲取單個對象數(shù)據(jù)的簡單方法,Django為數(shù)據(jù)的操作提供了諸多方便的功能,需要的朋友可以參考下

相對列表來說,有些時候我們更需要獲取單個的對象, `` get()`` 方法就是在此時使用的:

>>> Publisher.objects.get(name="Apress")
<Publisher: Apress>

這樣,就返回了單個對象,而不是列表(更準(zhǔn)確的說,QuerySet)。 所以,如果結(jié)果是多個對象,會導(dǎo)致拋出異常:

>>> Publisher.objects.get(country="U.S.A.")
Traceback (most recent call last):
  ...
MultipleObjectsReturned: get() returned more than one Publisher --
  it returned 2! Lookup parameters were {'country': 'U.S.A.'}

如果查詢沒有返回結(jié)果也會拋出異常:

>>> Publisher.objects.get(name="Penguin")
Traceback (most recent call last):
  ...
DoesNotExist: Publisher matching query does not exist.

這個 DoesNotExist 異常 是 Publisher 這個 model 類的一個屬性,即 Publisher.DoesNotExist。在你的應(yīng)用中,你可以捕獲并處理這個異常,像這樣:

try:
  p = Publisher.objects.get(name='Apress')
except Publisher.DoesNotExist:
  print "Apress isn't in the database yet."
else:
  print "Apress is in the database."

相關(guān)文章

最新評論