How to verify object creation in Django?
I want to verify that the object I created was really created, and return True or False 开发者_开发百科according to that:
obj = object(name='plop')
try:
obj.save()
return True
except ???:
return False
How can object creation be verified?
First of all - that's a not good practice that you are doing
2nd the only case when exception can happen is database connection fail or some constrains or required required fields not set.. in that case db-backend.OperationalError is raised
Update: on constrains fail there is a IntegrityError exception
save() can also raise other exceptions, such as ValidationError in django 1.2, or any arbitrary exception if the save() method has been overridden.
I don't see anything particularly wrong with attempting a save() and catching the exception. If for some reason you prefer to check a boolean return value than just catch the exception (not usually how it's done in python), then you have the right idea. Just change except ???: to except Exception:
After all you want to return False on any expected failure.
精彩评论