popolo - code simple..

popolo - code simple..

Masonite Project - Database Seeder Tutorial Example

Masonite Project - Database Seeder Tutorial Example

Theodoros Kafantaris's photo
Theodoros Kafantaris
·Apr 26, 2022·

2 min read

Table of contents

  • Creating Seeds
  • Run single seed
  • Run all seeds

In this tutorial, we will see how to create a database seeder in Masonite Project and what is command to create a seeder and how to run that seeder in Masonite Project. Let's follow a few steps to see how it's done.

Creating Seeds

You can create a seed file and seed class which can be used for keeping seed information and running it later. To create a seed run the command:

masonite-orm seed Product

This command is creating a seed file (product_table_seeder.py) in database/seeds folder.

product_table_seeder.py

"""ProductTableSeeder Seeder."""
from masoniteorm.seeds import Seeder
from app.models.Product import Product


class ProductTableSeeder(Seeder):
    def run(self):
        """Run the database seeds."""
        Product.create({
            "name": "Product 1",
            "details": "Description of product 1",
        })

Run single seed

Run the following command to seed the data to database only for Product.

masonite-orm seed:run Product

Run all seeds

If we want to run all the seeds we must add the appropriate seeders to database/seeds/database_seeder.py:

"""Base Database Seeder Module."""
from masoniteorm.seeds import Seeder
from .product_table_seeder import ProductTableSeeder
from .user_table_seeder import UserTableSeeder


class DatabaseSeeder(Seeder):
    def run(self):
        """Run the database seeds."""
        self.call(UserTableSeeder)
        self.call(ProductTableSeeder)

Then we can run the following command without any argument and seed all the data in the DB.

masonite-orm seed:run

Let's see what we can do if we want to run seeder to insert many records in our DB. Except for factories we can do the following using the python faker library. In the below example, we can see how to create 5 new Products in the DB.

"""ProductTableSeeder Seeder."""

from faker import Faker
from masoniteorm.seeds import Seeder
from app.models.Product import Product


class ProductTableSeeder(Seeder):
    def run(self):
        fake=Faker()
        for i in range(5):
            Product.create(
                {
                    "name": "Product {}".format(i),
                    "details": fake.text(),
                }
        )

That's it, now we are ready to create and run our seeds.

 
Share this