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

yipeiwu_com6年前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."

相关文章

Numpy之reshape()使用详解

Numpy之reshape()使用详解

如下所示: Numpy中reshape的使用方法为:numpy.reshape(a, newshape, order='C') 参数详解: 1.a: type:array_like(伪数...

linux中如何使用python3获取ip地址

前言 这篇文章主要介绍了linux中如何使用python3获取ip地址,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下。 一、不带参数...

Python 序列的方法总结

      最近在做Python 的项目,特地整理了下 Python 序列的方法。序列sequence是python中最基本的数据结构,...

基于Python os模块常用命令介绍

基于Python os模块常用命令介绍

1、os.name---判断现在正在实用的平台,Windows返回'nt';linux返回'posix' 2、os.getcwd()---得到当前工作的目录。 3、os.listdir(...

使用Python测试Ping主机IP和某端口是否开放的实例

使用Python测试Ping主机IP和某端口是否开放的实例

使用Python方法 比用各种命令方便,可以设置超时时间,到底通不通,端口是否开放一眼能看出来。 命令和返回 完整权限,可以ping通,端口开放,结果如下: 无root权限(省略了pi...