Django filter versus get for single object?

Django filter versus get for single object?

While at work, we use a particular pattern in Django for getting a single object. We first filter the queryset by the id or slug and then check if the queryset exists. If so, then we return the object otherwise we return none.

According to James Bennet, Django release manager and author of django-registration, this isn’t necessary,

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

I think the reason we avoid it is because the get() method requires that we use a try/except block and I rarely see exceptions being caught in our code. Not sure why that is, but Jeff Knupp suggests that writing Python with exception handling leads to cleaner code.

UPDATE: Some good books on Django design patterns and coding style:

Leave a Reply and Share Your Thoughts