Created
October 7, 2014 11:03
-
-
Save ergoithz/a2505c14a6269923ef82 to your computer and use it in GitHub Desktop.
initial_data attribute support for django models (like a fixture but only once model is created)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# myproject/myapp/management/__init__.py | |
from django.db.models.signals import post_syncdb | |
import myapp.models | |
def post_syncdb_handler(sender, **kwargs): | |
''' | |
Handler will be called on every syncdb to set initial data for models if `initial_data` attr | |
is set. | |
`initial_data` model attribute uses the same format of django fixtures but 'model' attribute | |
is ignored (model class is used instead). | |
:param sender: | |
:param kwargs: | |
:return: | |
''' | |
nmodels = 0 | |
nrows = 0 | |
for model in kwargs.get('created_models', ()): | |
irows = nrows | |
for row in getattr(model, 'initial_data', ()): | |
nrows += 1 | |
model(pk=row['pk'], **row['fields']).save() | |
if irows < nrows: | |
nmodels += 1 | |
if nmodels: | |
print 'Initial data set (%d rows) for %d models.' % (nrows, nmodels) | |
else: | |
print 'No initial data set.' | |
post_syncdb.connect(post_syncdb_handler, sender=myapp.models) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment