Quick hack today. Often I find myself wanting to get some django object, but in the case it doesn’t exist default it to some value. Specially I keep my end user configurable settings in my database. Typically I set this up with initial data so all the settings are already there, but sometimes I’ll add a setting and forgot to add it on some site instance.
def __init__(self, anycallable):
self.__call__ = anycallable
def get_or_default(name, default=None):
""" Get the config object or create it with a default. Always use this when gettings configs"""
object, created = Configuration.objects.get_or_create(name=name)
object.value = default
get_or_default = Callable(get_or_default)[/python]
Now I can safely call things like edit_all = Configuration.get_or_default(“Edit all fields”, “False”) which will return my configuration object with the value set as False if not specified. Much better than a 500 error. There are plenty of other uses for this type of logic. Get_or_return_none for example. The goal for me is to stop 500 errors from my own carelessness by having safe defaults.