Package: django-seeding
Django SeedingTable of ContentsIntroductionInstallationSimple ExampleFull Usage DocumentationSeeders ListAttributes ListRun MethodsFull ExamplesCSVFileModelSeeder (Recommended)JSONFileModelSeeder (Recommended)CSVFileSerializerSeederJSONFileSerializerSeederEmptySeeder (Recommended)ModelSeeder (Recommended)SerializerSeederSeederContributingContactLicenseIntroductionThis package helps develpoers tofillthe database withreal datainstead of filling it manually.Data can be presented asCSV File,JSON Fileorin-code.Dependency-Injectionalso available to inject your logic by specifying aserializer_classor writing your customseedmethod.InstallationInstalling using pip:pip install django-seeding:add'django_seeding'to yourINSTALLED_APPSsetting:INSTALLED_APPS = [
    ...
    'django_seeding',
]Simple ExampleLet's take a look at a quick example of usingCSVFileModelSeederseeder fromdjango-seedingto build a simple seeder to insert data in the database.django_seeding_example/models.py:from django.db import models


class M1(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()django_seeding_example/seeders.py:from django_seeding import seeders
from django_seeding.seeder_registry import SeederRegistry 
from django_seeding_example.models import M1

@SeederRegistry.register
class M1Seeder(seeders.CSVFileModelSeeder):
    model = M1
    csv_file_path = 'django_seeding_example/seeders_data/M1Seeder.csv'django_seeding_example/seeders_data/M1Seeder.csv:title,description
t1,d1
t2,d2Now you just need to run this commande:python manage.py seedFull Usage Documentation:Now lets go deeper into the different Seeders types with its details:Seeders List:CSVFileModelSeeder (Recommended)JSONFileModelSeeder (Recommended)CSVFileSerializerSeederJSONFileSerializerSeederEmptySeeder (Recommended)ModelSeeder (Recommended)SerializerSeederSeederAttributes ListIn general there is a way to know how to deal with these seeders easily:Model..Seeder needsmodelclass-attributeSerializer..Seeder needsserializer_classclass-attributeCSVFile..Seeder needscsv_file_pathclass-attributeJSONFile..Seeder needsjson_file_pathclass-attributeAll seeders can takes these optional class-attributes:id: str(So Recommended)This is what will be stored in the AppliedSeeder table to check if a seeder is already applied or notIt is recommended to set it as the seeder nameSo, set it and don't change it because when the value is changed it will be considerd as a new seeder and it will be applied again even that the old seeder with the old name is applieddefault value:str(type(seeder))priority: int|floatSeeders will be sorted depending on this attribute (lower-first)default value:float('inf')just_debug: boolThis attribute specify if the seeder will be applied when the server is in the production-mode or not depending in the DEBUG variable in settings fileDEBUG=False&just_debug=True-> don't applyDEBUG=False&just_debug=False-> applyDEBUG=True&just_debug=False-> applyDEBUG=True&just_debug=True-> applydefault value:FalseNotice:@SeederRegistry.registeris the decorator that register the seeder, so, if this decorator is not applied then the seeder will not be appliedModel seeders use bulk_create method, so, they are faster than Serializer seedersCSV file reader is using pandas for a better performance and less bugsUsing Model seeders means the fields names must match the fields you have defined in your modelUsing Serializer seeders means the fields names must match the fields you have defined in your serializeryou can defineget_class-methods instead of class-attributes as below:get_model
get_serializer_class
get_csv_file_path
get_json_file_path
get_id
get_priority
get_just_debugRun methods:To seed with a manual command (Recommended):python manage.py seedTo seed with runserver manually just add "--seed" in runserver command:python manage.py runserver --seedTo seed on runserver automatically just set in your project settings:SEEDING_ON_RUNSERVER = TrueNotice:If you setSEEDING_ON_RUNSERVER=Truein your settings file You can stop seeding in a runserver by using--dont-seedargumentpython manage.py runserver --dont-seedFull Examples:Here we will go deeper in the seeders classes and its detailsCSVFileModelSeeder (Recommended):Fastbulk_createseedernotice that the titles in thecsv-filehave to match the fields name in themodelmodels.pyclass M1(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()seeders.py@SeederRegistry.register
class M1Seeder(seeders.CSVFileModelSeeder):
    id = 'M1Seeder'
    priopity = 1
    model = M1
    csv_file_path = 'django_seeding_example/seeders_data/M1Seeder.csv'seeders_data/M1Seeder.csvtitle,description
t1,d1
t2,d2JSONFileModelSeeder (Recommended):Fastbulk_createseedernotice that the keys in thejson-filehave to match the fields name in themodelmodels.pyclass M2(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()seeders.py@SeederRegistry.register
class M2Seeder(seeders.JSONFileModelSeeder):
    id = 'M2Seeder'
    priopity = 2
    model = M2
    json_file_path = 'django_seeding_example/seeders_data/M2Seeder.json'seeders_data/M2Seeder.json[
    {
        "title": "json t1",
        "description": "json d1"
    },
    {
        "title": "json t2",
        "description": "json d2"
    }
]CSVFileSerializerSeeder:Slow one-by-one seedernotice that the titles in thecsv-filehave to match the fields name in theserializerThis seeder is used to inject a serializer to implement custom create logicmodels.pyclass M3(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()serializers.pyclass M3Serializer(serializers.ModelSerializer):
    class Meta:
        model = M3
        fields = ['title', 'description']

    def create(self, validated_data):
        validated_data['title'] = '__' + validated_data['title'] + '__'
        validated_data['description'] = '__' + validated_data['description'] + '__'
        return super().create(validated_data)seeders.py@SeederRegistry.register
class M3Seeder(seeders.CSVFileSerializerSeeder):
    id = 'M3Seeder'
    priopity = 3
    serializer_class = M3Serializer
    csv_file_path = 'django_seeding_example/seeders_data/M3Seeder.csv'seeders_data/M3Seeder.csvtitle,description
t1,d1
t2,d2JSONFileSerializerSeeder:Slow one-by-one seedernotice that the keys in thejson-filehave to match the fields name in theserializerThis seeder is used to inject a serializer to implement custom create logicmodels.pyclass M4(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()serializers.pyclass M4Serializer(serializers.ModelSerializer):
    class Meta:
        model = M4
        fields = ['title', 'description']

    def create(self, validated_data):
        validated_data['title'] = '__' + validated_data['title'] + '__'
        validated_data['description'] = '__' + validated_data['description'] + '__'
        return super().create(validated_data)seeders.py@SeederRegistry.register
class M4Seeder(seeders.JSONFileSerializerSeeder):
    id = 'M4Seeder'
    priopity = 4
    serializer_class = M4Serializer
    json_file_path = 'django_seeding_example/seeders_data/M4Seeder.json'seeders_data/M4Seeder.json[
    {
        "title": "json t1",
        "description": "json d1"
    },
    {
        "title": "json t2",
        "description": "json d2"
    }
]EmptySeeder (Recommended):Fastbulk_createseedermodels.pyclass M5(models.Model):
    title = models.CharField(max_length=100, null=True)
    description = models.TextField(null=True)seeders.py@SeederRegistry.register
class M5Seeder(seeders.EmptySeeder):
    id = 'M5Seeder'
    priopity = 5
    model = M5
    records_count = 2ModelSeeder (Recommended):Fastbulk_createseedernotice that the keys in thedataclass-attribute have to match the fields name in themodelmodels.pyclass M6(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()seeders.py@SeederRegistry.register
class M6Seeder(seeders.ModelSeeder):
    id = 'M6Seeder'
    priopity = 6
    model = M6
    data = [
        {
            "title": "in-code t1",
            "description": "in-code d1"
        },
        {
            "title": "in-code t2",
            "description": "in-code d2"
        },
    ]SerializerSeeder:Slow one-by-one seedernotice that the keys in thedataclass-attribute have to match the fields name in theserializerThis seeder is used to inject a serializer to implement custom create logicmodels.pyclass M7(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()serializer.pyclass M7Serializer(serializers.ModelSerializer):
    class Meta:
        model = M7
        fields = ['title', 'description']

    def create(self, validated_data):
        validated_data['title'] = '__' + validated_data['title'] + '__'
        validated_data['description'] = '__' + validated_data['description'] + '__'
        return super().create(validated_data)seeders.py@SeederRegistry.register
class M7Seeder(seeders.SerializerSeeder):
    id = 'M7Seeder'
    priopity = 7
    serializer_class = M7Serializer
    data = [
        {
            "title": "in-code t1",
            "description": "in-code d1"
        },
        {
            "title": "in-code t2",
            "description": "in-code d2"
        },
    ]Seeder:Here you can write your logic as you want in the seed methodmodels.pyclass Post(models.Model):
    content = models.TextField()


class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField()seeders.py@SeederRegistry.register
class CustomSeeder(seeders.Seeder):
    id = 'CustomSeeder'
    priopity = 8
    
    def seed(self):
        post1 = Post.objects.create(content='post1')
        post2 = Post.objects.create(content='post1')

        comment1 = Comment.objects.create(post=post1, content='comment1')
        comment2 = Comment.objects.create(post=post1, content='comment2')
        comment3 = Comment.objects.create(post=post2, content='comment3')
        comment4 = Comment.objects.create(post=post2, content='comment4')ContributingIf you have suggestions for how Django Seeding could be improved, or want to report a bug, open an issue! We'd love all and any contributions.For more, check out theContributing Guide.ContactSuliman Awad -sulimanawadstudy@gmail.com-LinkedinProject Link:https://github.com/suliman-99/django-seedingLicenseMIT LicenseCopyright (c) 2023 Suliman AwadFor more, check out theLicense File.