A simple method for getting data from a single object in the Python Django framework

Source: Internet
Author: User
This article describes how to obtain data from a single object in the Python Django framework. Django provides many convenient functions for data operations, for more information, see the following list. sometimes we need to obtain a single object. the ''Get () ''method is used at this time:

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

In this way, a single object is returned, instead of a list (more accurately, QuerySet ). Therefore, if the result is multiple objects, an exception is thrown:

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

If no query result is returned, an exception is thrown:

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

The DoesNotExist exception is an attribute of the Publisher model class, that is, Publisher. DoesNotExist. In your application, you can capture and handle this exception, like this:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.