Skip to content

Instantly share code, notes, and snippets.

@dokterbob
Created June 21, 2012 14:45
Show Gist options
  • Save dokterbob/2966162 to your computer and use it in GitHub Desktop.
Save dokterbob/2966162 to your computer and use it in GitHub Desktop.
Example of loosely coupling Django apps using settings.
from django.db import models
# Import the PROJECT_MODEL string from the current app's settings
from .settings import PROJECT_MODEL
class Task(models.Model):
"""
Instead of explicitly giving the model for the FK as a Python object or
explicitly stating a string in the form '<app>.<modelname>', we'll use
the imported setting.
In really ridiculous occasions we could even make this one conditional::
if PROJECT_MODEL:
project = models.ForeignKey(PROJECT_MODEL)
(Yes, this works.)
"""
# Instead of explicitly stating the string
project = models.ForeignKey(PROJECT_MODEL)
from django.conf import settings
"""
Using 'federated' settings really helps keeping oversight of
the settings for a particular Django app. This way we allways
know *where* settings are, *what* they are named and what their
*defaults* are.
In a typical use case you would document every single setting
with a piece of comment.
In the Django `settings.py`, this would look like this::
# Use Swiss cheese instead of projects.Project for linking tasks to.
<APP_NAME>_PROJECT_MODEL = 'cheese.Swisscheese'
"""
# The project model, allowing a generic way to link tasks to whatever it
# is they relate to - and allow full flexibility on how Projects will be
# implemented.
#
# The default is to use the Project model from the projects app.
PROJECT_MODEL = getattr(settings, '<APP_NAME>_PROJECT_MODEL', 'projects.Project')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment