简体   繁体   中英

Generating fixtures in django

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.

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.

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM