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.
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)
You can write your own Migration
and insert new records (or do any other migration you want).
See this article item in Django
docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With