Whenever I do this:
thepost = Content.objects.get(name="test")
It always throws an error when nothing is found. How do I handle it?
Contact.objects.all() returns url, email, person and ID of row in Bonus.
Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
try:
thepost = Content.objects.get(name="test")
except Content.DoesNotExist:
thepost = None
Use the model DoesNotExist exception
Often, it is more useful to use the Django shortcut function get_object_or_404
instead of the API directly:
from django.shortcuts import get_object_or_404
thepost = get_object_or_404(Content, name='test')
Fairly obviously, this will throw a 404 error if the object cannot be found, and your code will continue if it is successful.
You can also catch a generic DoesNotExist. As per the docs at http://docs.djangoproject.com/en/dev/ref/models/querysets/
from django.core.exceptions import ObjectDoesNotExist
try:
e = Entry.objects.get(id=3)
b = Blog.objects.get(id=1)
except ObjectDoesNotExist:
print "Either the entry or blog doesn't exist."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With