Reputation: 5843
I have an app that can generate some gibberish model instances on queue. As opposed to having static fixture initial_data, I would like to have something like following during migrations:
if IS_DEBUG and not IS_TEST:
(create_post() for _ in xrange(100))
(create_user() for _ in xrange(100))
I know how to load static fixtures in django, but I would like to have more control over fake data I load into my application.
Just a note - this is not for unit/func/anything tests, but to populate the database to be able to browse the development version of a website and look around.
What is the best way to accomplish this? Custom south migration?
UPDATE: Question that concerns me with south migrations, if I change a model in a migration after that custom migration which populates data - it'll be a bit messy. For example:
0001_initial
0002_generate_fixtures
0003_add_field_to_a_model
So now I'll have to remove 0002_generate_fixtures
and create new migration 0004_generate_fixtures
. That gets messy very quickly.
Upvotes: 0
Views: 1481
Reputation: 9117
I think the best way is to write simple custom script to fill the database. Don't use South for this purpose.
Simply run your custom script when you want to fill database:
fill_db.py:
from django.conf import settings
def fill_db()
if settings.IS_DEBUG and not settings.IS_TEST:
for i in xrange(100):
Post.objects.create()
User.objects.create()
You can also add this script to the django management commands:
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
fill_db()
Upvotes: 1
Reputation: 5843
Serafeim's and nieka's answers have been very helpful, at the end of the day I decided to go with a custom management command in app_name/management/commands/populatedb.py
.
Now, I can simply run python manage.py populatedb
to dynamically populate my database.
Upvotes: 2
Reputation: 15104
I've used the factory_boy (https://github.com/rbarrois/factory_boy) with greate success to create custom fixtures (for tests or just populating the database).
Copying from the project's README:
factory_boy is a fixtures replacement based on thoughtbot's factory_girl.
Its features include:
Straightforward syntax Support for multiple build strategies (saved/unsaved instances, attribute dicts, stubbed objects) Powerful helpers for common cases (sequences, sub-factories, reverse dependencies, circular factories, ...) Multiple factories per class support, including inheritance Support for various ORMs (currently Django, Mogo, SQLAlchemy)
Upvotes: 1