views:

39

answers:

1

If I have a models.py like

class WidgetType(models.Model):
     name = models.CharField(max_length=200)

class Widget(models.Model):
     typeid = models.ForeignKey(WidgetType)
     data = models.CharField(max_length=200)

How can I build in a set of built in constant values for WidgetType when I know I'm only going to have a certain few types of widget? Clearly I could fire up my admin interface and add them by hand, but I'd like to simplify configuration by having it built into the python.

+3  A: 

You could use fixtures:

http://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-data-with-fixtures

Strictly speaking, fixtures aren't part of the models, or any python code for that matter. If you really need it in your python code, you could listen for the post_syncdb signal and insert your data through the ORM, e.g.:

from django.db.models.signals import post_syncdb

def insert_initial_data(sender, app, created_models, verbosity, **kwargs):
    if WidgetType in created_models:
        for name in ('widgettype1', 'widgettype2', 'widgettype3'):
            WidgetType.objects.get_or_create(name=name)

post_syncdb.connect(insert_initial_data)
piquadrat