Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initial_data fixture management in django

The django projet I'm working on has a ton of initial_data fixture data. It seems by default the only way to have data load automatically is to have a file in your app folder called fixtures, and the file needs to be named initial_data.ext (ext being xml or json or yaml or something).

This is really unflexable, I think. I'd rather have a fixtures folder, and then inside that a initial_data folder, and then inside there, one file for each model in that app. Or something to that effect. IS this possible to do in django now? Or maybe some other scheme of better fixture organization.

like image 624
priestc Avatar asked Dec 09 '10 16:12

priestc


People also ask

How do I use fixtures in Django?

Providing data with fixtures The most straightforward way of creating a fixture if you've already got some data is to use the manage.py dumpdata command. Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML (with PyYAML installed) documents.

Can we use MySQL with Django?

Django officially supports the following databases: PostgreSQL. MariaDB. MySQL.


2 Answers

In my experience, hard-coded fixtures are a pain to write and a pain to maintain. Wherever a model change breaks a fixture, the Django initial load will return a very unfriendly error message and you will end-up adding a bunch a of print's in the Django core in order to find where the problem is coming from.

One of the developer I work with has developed a very good library to overcome this problem, it's called django-dynamic-fixture and we really to love it. Here is how it works:

Suppose you have this models:

class Author(models.Model):
    name = models.CharField()

class Book(models.Model):
    author = models.ForeingKey(Author, required=True)
    title = models.CharField()

In order to create a book instance in your test, all you have to do is

from django_dynamic_fixture import get
from app import Book

class MyTest(TestCase):
    def setUp(self):
        self.book = get(Book)

The django-dynamic-fixture automatically creates for you any dependencies that are required for the Book model to exist. This is just a simple example but the library can handle very complex model structures.

like image 93
Cesar Canassa Avatar answered Sep 21 '22 20:09

Cesar Canassa


You can reorganize your initial data fixtures however you want and then write a post_syncdb signal handler which loads them. So it will then be automatically loaded on syncdb, according to the logic defined by you.

See: https://docs.djangoproject.com/en/1.3/ref/signals/#post-syncdb

like image 2
Botond Béres Avatar answered Sep 19 '22 20:09

Botond Béres