Populate Django database

后端 未结 2 1208
旧时难觅i
旧时难觅i 2021-02-05 10:46

I\'m developing a Django application which stores user information like their address, phone number, name, etc.

I\'ve worked with PHP\'s Faker library and the seeder inc

2条回答
  •  一个人的身影
    2021-02-05 11:32

    To get it done in a nice way you'll need a combination of Factory Boy, Faker and custom management commands.

    Factory Boy allows you to create templates for producing valid objects and Faker generates fake data.

    When you install Factory Boy, pip install factory_boy, you also get Faker.

    Given,

    from django.db import models
    
    
    class User(models.Model):
        name = models.CharField(max_length=64)
        address = models.CharField(max_length=128)
        phone_number = models.CharField(max_length=32)
    

    You can define a Factory as follows:

    import factory  
    import factory.django
    
    class UserFactory(factory.django.DjangoModelFactory):  
        class Meta:
            model = User
    
        name = factory.Faker('name')
        address = factory.Faker('address')
        phone_number = factory.Faker('phone_number')
    

    Then, you can create fake users by calling UserFactory.create().

    One way to get your 200 fake users would be to jump into the shell, python manage.py shell, and do:

     >>> # import UserFactory here
     >>> for _ in range(200):
     ...     UserFactory.create()
    

    Another way, which can give you a lot more flexibility, is to create a custom management command.

    For example, create seed.py (this will be the management command name) in the directory /management/commands (to have it discovered by Django) with the following:

    # /management/commands/seed.py
    from django.core.management.base import BaseCommand
    
    # import UserFactory here
    
    
    class Command(BaseCommand):
        help = 'Seeds the database.'
    
        def add_arguments(self, parser):
            parser.add_argument('--users',
                default=200,
                type=int,
                help='The number of fake users to create.')
    
        def handle(self, *args, **options):
            for _ in range(options['users']):
                UserFactory.create()
    

    And, you'd run it via the command-line with python manage.py seed or python manage.py seed --users 50 for example.

提交回复
热议问题