| | 1 | ''It is very simple example, please, read something more complex if you need.'' |
| | 2 | |
| | 3 | Fixtures are very powerful to play with your database sample data during development process. |
| | 4 | After each '''python manage.py reset <myapp>''' command you need to populate database with sample data again and again using admin interface. It's quite boring, isn't it? |
| | 5 | With fixtures our life became more comfortable and easy. Look at this example. |
| | 6 | Lets imagine that you have some data in db, so we can dump it. Even if your models have ForeignKeys or any kind of *To* relations. |
| | 7 | |
| | 8 | First we need to define fixtures dir in settings file: |
| | 9 | |
| | 10 | {{{ |
| | 11 | FIXTURE_DIRS = ( |
| | 12 | '/path/to/myapp/fixtures/', |
| | 13 | ) |
| | 14 | }}} |
| | 15 | |
| | 16 | Lets dump our data: |
| | 17 | |
| | 18 | {{{ |
| | 19 | cd /path/to/myapp/fixtures |
| | 20 | python manage.py dumpdata --format=json myapp > initial_data.json |
| | 21 | }}} |
| | 22 | |
| | 23 | Reset: |
| | 24 | |
| | 25 | {{{ |
| | 26 | python manage.py reset myapp |
| | 27 | |
| | 28 | You have requested a database reset. |
| | 29 | This will IRREVERSIBLY DESTROY any data for |
| | 30 | the "myapp" application in the database "mydb". |
| | 31 | Are you sure you want to do this? |
| | 32 | |
| | 33 | Type 'yes' to continue, or 'no' to cancel: yes |
| | 34 | }}} |
| | 35 | |
| | 36 | Now we have clean DB, lets populate it with our sample data: |
| | 37 | |
| | 38 | {{{ |
| | 39 | python manage.py syncdb |
| | 40 | Loading 'initial_data' fixtures... |
| | 41 | Installing json fixture 'initial_data' from '/path/to/myapp/fixtures/'. |
| | 42 | Installed 24 object(s) from 1 fixture(s) |
| | 43 | }}} |