Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In django, how can I include some default records in my models.py?

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.

like image 715
kdt Avatar asked May 02 '10 10:05

kdt


2 Answers

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_migrate signal and insert your data through the ORM, e.g.:

from django.db.models.signals import post_migrate

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_migrate.connect(insert_initial_data)
like image 62
Benjamin Wohlwend Avatar answered Sep 28 '22 03:09

Benjamin Wohlwend


You can write your own Migration and insert new records (or do any other migration you want).

See this article item in Django docs.

like image 27
GProst Avatar answered Sep 28 '22 03:09

GProst