Django get_or_default

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.

class Callable:
    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)
        if created:
            object.value = default
            object.save()
        return object
    get_or_default = Callable(get_or_default)

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.

2 thoughts on “Django get_or_default”

  1. Always nice to find your blog in my Google results. What happens when you use that configuration value in lots of places and are inconsistent with the default?

  2. John I thought you were a spam bot writing about how great my blog is.

    It’s certainly a hack solution. Fixtures would be better but deploying them is harder. One could make a south fixture http://south.readthedocs.org/en/latest/fixtures.html to deal with migrations but that has it’s own issues. It’s annoying to have tons of fixtures laying around for each new config value. Seems better to have them in one place but then how do you deal with schema migrations?

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*