Django Fixture
Agenda
What is Django Fixture?
Syntax
Example
Insert Data to Django models
Supported Format and Data structures
What is
Django
Fixture?
Collection of data that is in a
specific format.
Use to load initial data into
Django models.
Fixture can be written in JSON,
XML and YAML format.
Syntax - Load fixturedata into Database tables
python manage.py loaddata fixture_file.json
This will read fixture data from the fixture file and insert the data
into Database table.
Example - Add data to
Student model
Create Model
#models.py
class Student(models.Model):
name = models.CharField(max_length=50)
company = models.CharField(max_length=50)
city = models.CharField(max_length=50)
Run
Command
python manage.py
makemigrations
python manage.py migrate
Insert Data to
Django models
Step 1 - Create
folder "Fixture"
inside app folder.
Step 2 –
Create json file
under the folder.
Ex -
student_data.json
Specify list
of JSON
objects of
data in file
[
{
"model": "myapp.Student",
"pk": 1,
"fields": {
"name": "Amit",
"company": "Acenture",
"city": "Pune" ,
}
},
]
Load fixture data into Database tables
python manage.py loaddata fixture_file.json
Check the Database
After run loaddata command we
can see data is inserted into
database.
Supported
Format and
Data
structures
JSON
XML
YAML
Using YAML file
The same information can be put into a YAML and that would look like
following:
- model: myapp.person
pk: 1
fields:
name: Amit
company: Acenture
city: Pune
Using XML file
The same information can be put into a XML and that would look like following:
<?xml version="1.0" encoding="UTF-8"?>
<django-objectsversion="1.0">
<object pk="1" model="myapp.Student">
<field type="CharField" name="name">Amit</field>
<field type="CharField" name="company">Accenture</field>
<field type="CharField" name="city">Pune</field>
</object>
</django-objects>
Thank You !

Django fixture