Django Patterns

Configurable Options for Common SituationsΒΆ

Warning

This is just a stub document. It will be fleshed out more. If you wish to comment on it, please e-mail coreyoordt at gmail.

A few, well-known of variations (e.g. Use django.contrib.sites?)

models.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.db import models
from coolapp.settings import MULTIPLE_SITES, SINGLE_SITE

if MULTIPLE_SITES or SINGLE_SITE:
    from django.contrib.sites.models import Site

class Entry(models.Model):
    title = models.CharField(max_length=100)
    # Other stuff
    
    if MULTIPLE_SITES:
        sites = models.ManyToManyField(Site)
    if SINGLE_SITE:
        sites = models.ForeignKey(Site)

Another example:

models.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.db import models
from myapp.settings import USE_TAGGING

if USE_TAGGING:
    from tagging.fields import TagField

class Entry(models.Model):
    title = models.CharField(max_length=100)
    # Other stuff
    
    if USE_TAGGING:
        tags = TagField()

You can provide for optional field settings.

Import the setting from your own apps settings

Based on that setting, you can optionally import classes. And in your model definition...

Optionally declare fields. The only drawback of this depends on the type of field. Changing your mind after the initial table creation might require you to either manually add the field or drop the table and syncdb again.

Link to way to do migration with south if field is added.