Django filter versus get for single object? Django filter versus get for single object? django django

Django filter versus get for single object?


get() is provided specifically for this case. Use it.

Option 2 is almost precisely how the get() method is actually implemented in Django, so there should be no "performance" difference (and the fact that you're thinking about it indicates you're violating one of the cardinal rules of programming, namely trying to optimize code before it's even been written and profiled -- until you have the code and can run it, you don't know how it will perform, and trying to optimize before then is a path of pain).


You can install a module called django-annoying and then do this:

from annoying.functions import get_object_or_Noneobj = get_object_or_None(MyModel, id=1)if not obj:    #omg the object was not found do some error stuff


1 is correct. In Python an exception has equal overhead to a return. For a simplified proof you can look at this.

2 This is what Django is doing in the backend. get calls filter and raises an exception if no item is found or if more than one object is found.