Seeders
Table of contents
- Introduction
- Writing a seeder
- Building on another feature’s data
- Seeding your product’s own content
- Running seeders
- See also
Introduction
A seeder fills the database with sample or starting data, such as a few users or some notes to look at. Each feature keeps its own in seeders.py, and db:seed runs them all.
from splent_framework.seeders.BaseSeeder import BaseSeeder
from splent_io.splent_feature_notes.models import Note
class NotesSeeder(BaseSeeder):
def run(self):
self.seed([
Note(title="Welcome", content="Your first note.", published=True),
Note(title="Draft", content="Not ready yet.", published=False),
])
splent db:seed
Writing a seeder
Extend BaseSeeder and write run(). self.seed(objects) adds a list of objects of one model, commits, and returns them with their ids.
- A list that mixes models raises
ValueError. - A duplicate key or a broken constraint rolls back and raises
SeederError. - An empty list returns
[].
A seeders.py may hold several seeder classes, with any name. db:seed runs every class in it that extends BaseSeeder.
Building on another feature’s data
from splent_framework.seeders.BaseSeeder import BaseSeeder
from splent_io.splent_feature_notes.models import Note
from splent_io.splent_feature_reports.models import ReportEntry
class ReportsSeeder(BaseSeeder):
def run(self):
notes = Note.query.filter_by(published=True).all()
self.seed([ReportEntry(note_id=note.id) for note in notes])
Seeders run in the order the features load, the UVL order with each refiner after its base. When reports requires notes in the model, the notes exist by the time this runs. There is no priority to set.
Seeding your product’s own content
What one product says about itself, such as its about page, goes in the product’s src/<product>/seeders.py. Product seeders run after every feature seeder.
class AboutSeeder(BaseSeeder):
replaces = ("splent_io.splent_feature_about",)
def run(self):
...
replaces skips the seeders of those features, so your product takes over their content without forking them.
Running seeders
splent db:seed # every seeder, in load order
splent db:seed notes # one feature, or the product's name
splent db:seed --reset -y # delete the data first, keep the tables
db:seed refuses to run in production. See db:seed.
See also
db:seed, the command that runs seeders.- Repositories, the other way to write data.