在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的Django框架中的静态资源管理器django-pipeline

 django-pipeline 是一个 Django 下非常方便的静态资源管理 app,尤其是 1.2 版本之后,利用 django-staticfiles 的collect...

Python获取任意xml节点值的方法

本文实例讲述了Python获取任意xml节点值的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: utf-8 -*- import xml.dom.mini...

Python 将RGB图像转换为Pytho灰度图像的实例

问题: 我正尝试使用matplotlib读取RGB图像并将其转换为灰度。 在matlab中,我使用这个: img = rgb2gray(imread('image.png'));...

各个系统下的Python解释器相关安装方法

Python下载 Python最新源码,二进制文档,新闻资讯等可以在Python的官网查看到: Python官网:http://www.python.org/ 你可以在一下链接中下载Py...

关于python中plt.hist参数的使用详解

关于python中plt.hist参数的使用详解

如下所示: matplotlib.pyplot.hist( x, bins=10, range=None, normed=False, weights=None, c...