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.

[python]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)[/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.

By David

I am a supporter of free software and run Burke Software and Consulting LLC. I am always looking for contract work especially for non-profits and open source projects. Open Source Contributions I maintain a number of Django related projects including GlitchTip, Passit, and django-report-builder. You can view my work on gitlab. Academic papers Incorporating Gaming in Software Engineering Projects: Case of RMU Monopoly in the Journal of Systemics, Cybernetics and Informatics (2008)

2 comments

  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?

    Like

    1. 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?

      Like

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: