Is there a possibility to return none if no results are found by a object.get()
function call?
I know it throws an exception by default, but I want to return none from it.
Asked
Active
Viewed 361 times
1

Abdul Rehman
- 2,313
- 2
- 15
- 14
-
2Use `filter(
).first()`, it returns `None` if nothing is found. – Ashwini Chaudhary Aug 09 '16 at 13:26
1 Answers
4
You can do it with exceptions like:
try:
object = Model.objects.get(foo='bar')
except Model.DoesNotExist:
object = None

Aamish Baloch
- 1,200
- 12
- 9
-
1You can even override `def get(self)` in your custom ModelManager to change that behavior. – Andrii Zarubin Aug 09 '16 at 14:04