How to provide initial data for modelsLink to this heading
It’s sometimes useful to prepopulate your database with hard-coded data when you’re first setting up an app. You can provide initial data with migrations or fixtures.
Provide initial data with migrationsLink to this heading
To automatically load initial data for an app, create a data migration. Migrations are run when setting up the test database, so the data will be available there, subject to some limitations.
Provide data with fixturesLink to this heading
You can also provide data using fixtures,
however, this data isn’t loaded automatically, except if you use
TransactionTestCase.fixtures.
Ένα fixture είναι μια συλλογή από δεδομένα την οποία το Django ξέρει πως να την κάνει import σε μια βάση δεδομένων. Ο πιο ευθύς τρόπος να δημιουργήσετε ένα fixture, αν έχετε ήδη κάποια data, είναι να χρησιμοποιήσετε την διαχειριστική εντολή manage.py dumpdata. Ή, μπορείτε να γράψετε τα fixtures με το χέρι. Τα fixtures μπορούν να γραφτούν σε μορφή JSON, XML ή YAML (με το PyYAML εγκατεστημένο, φυσικά) αρχείων. Το εγχειρίδιο για serialization περιέχει περισσότερες λεπτομέρειες σχετικά με αυτού του είδους των υποστηριζόμενων μορφών serialization.
As an example, though, here’s what a fixture for a Person model might look
like in JSON:
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Paul",
"last_name": "McCartney"
}
}
]
Και εδώ φαίνεται το ίδιο fixture σε μορφή YAML:
- model: myapp.person
pk: 1
fields:
first_name: John
last_name: Lennon
- model: myapp.person
pk: 2
fields:
first_name: Paul
last_name: McCartney
Θα αποθηκεύσετε αυτά τα δεδομένα σε ένα φάκελο fixtures μέσα στην εφαρμογή σας.
You can load data by calling manage.py loaddata
<fixturename>, where <fixturename> is the name of the fixture file
you’ve created. Each time you run loaddata, the data will be read
from the fixture and reloaded into the database. Note this means that if you
change one of the rows created by a fixture and then run loaddata
again, you’ll wipe out any changes you’ve made.
Tell Django where to look for fixture filesLink to this heading
By default, Django looks for fixtures in the fixtures directory inside each
app for, so the command loaddata sample will find the file
my_app/fixtures/sample.json. This works with relative paths as well, so
loaddata my_app/sample will find the file
my_app/fixtures/my_app/sample.json.
Django also looks for fixtures in the list of directories provided in the
FIXTURE_DIRS setting.
To completely prevent default search form happening, use an absolute path to
specify the location of your fixture file, e.g. loaddata /path/to/sample.