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

相关文章

python 简单照相机调用系统摄像头实现方法 pygame

python 简单照相机调用系统摄像头实现方法 pygame

如下所示: # -*- coding: utf-8 -*- from VideoCapture import Device import time import pyg...

在windows下Python打印彩色字体的方法

本文讲述了Python在windows下打印彩色字体的方法。分享给大家供大家参考,具体如下: ############################################...

详解Python中的strftime()方法的使用

 strftime()方法转换成一个元组或struct_time表示时间所指定的格式参数所返回gmtime()或localtime()为一个字符串。 当t不设置,所返回当前时间...

Python3.6简单操作Mysql数据库

本文为大家分享了Python3.6操作Mysql数据库的具体实例,供大家参考,具体内容如下 安装pymysql 参考https://github.com/PyMySQL/PyMySQL...

Django模板语言 Tags使用详解

Tags # 普通for循环 <ul> {% for user in user_list %} <li>{{ user.name }}</li&...