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