Reputation: 26502
This is a code snippet I wrote, which I consider is not Pythonic basically because of the if condition ladder.
This snippet is of a custom class that is used for backend processing,
def _get_item(self, **kwargs):
""" returns an object if object exists else None"""
return self.model.objects.get_object_or_none(**kwargs)
def get_object(self, info=None):
""" gets an object with given info """
if info:
self._validate_info(info=info)
name = self._info.get('name', '')
slug = self._info.get('slug', '')
if slug:
obj = self._get_item(slug=slug)
elif name:
obj = self._get_item(name=name)
else:
obj = self._get_item(name=name, slug=slug)
if obj:
return obj
here I need to optimize get_object()
method. the ._validate_info()
validates the given info
which basically checks and stores the required values in self._info
which is a dictionary, later retrieved with .get()
method.
How do I make this code Pythonic and less mess?
Upvotes: 0
Views: 93
Reputation: 31
There is a function in Django that helps you gets a value from a model or return a 404
from Django.shortcuts import get_object_or_404
get_object_or_404(Model, slug=slug)
Upvotes: 0
Reputation: 2055
Assuming that self._info
only contains name
and slug
data, you could write something like:
def get_object(self, info=None):
self._validate_info(info)
return self._get_item(**self._info)
To explain a bit more:
if obj:
return obj
# end of function
is equivalent to:
if obj:
return obj
else:
return None
And that is the same as just doing return obj
with no if test (assuming obj
is only falsy if it's None
).
Upvotes: 2