28
loading...
This website collects cookies to deliver better user experience
# main/models.py
from django import models
class Book(models.Model):
name = models.CharField(max_length=50)
author = models.CharField(max_length=20)
fixtures
at app level (in our app Main), or we can have all our fixtures at project level by defining FIXTURE_DIRS
in our settings.py
. # my_project/setting.py
FIXTURE_DIRS = BASE_DIR / "fixtures"
fixtures
at project level. Here, we are going to create our fixtures, which can be any of the following formats:book.json
. I prefer to name the fixtures after the app that their models belong to.# fixtures/cars.json
[
{
"model": "main.book",
"pk": 1,
"fields": {
"name": "Atomic Habits",
"author": "James Clear",
}
},
{
"model": "main.book",
"pk": 2,
"fields": {
"name": "Permanent Record",
"author": "Edward Snowden",
}
}
]
python manage.py loaddata cars.json
python manage.py makemigrations --empty main
# Generated by Django 3.0.11 on 2021-12-15 08:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
]
App Registry - A registry of all your apps, including
historical versions of their models.
Schema Editor - This is what is used to manually
effect database schema changes, (enforce changes to database)
def load_initial_data(apps, schema_editor):
# get our model
# get_model(appname, modelname)
book_model = apps.get_model('main', 'Book')
book_model.objects.create (
name = "Atomic Habits", author = "James Clear"
)
book_model.objects.create (
name = "Permanent Record", author = "Edward Snowden"
)
# Generated by Django 3.0.11 on 2021-12-15 08:35
from django.db import migrations
def load_initial_data(apps, schema_editor):
# get our model
# get_model(appname, modelname)
book_model = apps.get_model('main', 'Book')
book_model.objects.create (
name = "Atomic Habits", author = "James Clear"
)
book_model.objects.create (
name = "Permanent Record", author = "Edward Snowden"
)
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
]
load_initial_data
function to the operations
list in our migration file:operations = [
migrations.RunPython(load_initial_data),
]
# Generated by Django 3.0.11 on 2021-12-15 08:35
from django.db import migrations
def load_initial_data(apps, schema_editor):
# get our model
# get_model(appname, modelname)
book_model = apps.get_model('main', 'Book')
book_model.objects.create (
name = "Atomic Habits", author = "James Clear"
)
book_model.objects.create (
name = "Permanent Record", author = "Edward Snowden"
)
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.RunPython(load_initial_data),
]
python manage.py migrate