在Python的Django框架中获取单个对象数据的简单方法

yipeiwu_com5年前Python基础

相对列表来说,有些时候我们更需要获取单个的对象, `` get()`` 方法就是在此时使用的:

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

这样,就返回了单个对象,而不是列表(更准确的说,QuerySet)。 所以,如果结果是多个对象,会导致抛出异常:

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

如果查询没有返回结果也会抛出异常:

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

这个 DoesNotExist 异常 是 Publisher 这个 model 类的一个属性,即 Publisher.DoesNotExist。在你的应用中,你可以捕获并处理这个异常,像这样:

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

相关文章

Python 的 with 语句详解

一、简介 with是从Python 2.5 引入的一个新的语法,更准确的说,是一种上下文的管理协议,用于简化try…except…finally的处理流程。with通过__enter__...

Python 3.x 判断 dict 是否包含某键值的实例讲解

查询资料得 Python 可以使用两种方式判断字典是否包含某键值 1、(dict.has_key('keyname')) 2、('keyname' in dict) 觉得第二种方式太过丑...

mac PyCharm添加Python解释器及添加package路径的方法

mac PyCharm添加Python解释器及添加package路径的方法

一、背景 PyCharm执行Python时,找不到自己安装的package,例如pandas、numpy、scipy、scikit等,在执行时报如下错误ImportError: No...

python利用跳板机ssh远程连接redis的方法

公司服务器的mysql和redis连接都需要有跳板机,网上有很多python ssh远程连接mysql的,那天我研究了下,利用sshtunnel模块连接上了redis,具体如下: f...

python启动办公软件进程(word、excel、ppt、以及wps的et、wps、wpp)

复制代码 代码如下:#-*- coding:utf-8 -*- from win32com.client import Dispatch import time def start_of...