Populate django database

I am developing a Django application that stores user data such as their address, phone number, name, etc.

I worked with PHP Faker and the seeder included in Laravel. I was able to populate the database with fake data, but now I am working with Django.

I would like to fill out a table of my users about 200 entries. But I do not want the entries to be random strings. I want this to be fake data that I can get with Laravel. I do not know how to do that.

What do I need to do to save fake data?

This is for displaying to the end users of the application with some entries so that it can see statistics and other things. Data must remain in the database. I tried to use unit tests, but it deletes the database after unit test completes.

Thanks!

+5
source share
2 answers

@ user3186459 This is a great question.

To do this well, you'll need a combination of Factory Boy , Faker, and customizable control commands .

Factory Boy lets you create patterns to create valid objects, and Faker generates fake data.

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

Considering,

 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 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') 

You can then create fake users by calling UserFactory.create() .

One way to get your 200 fake users is to go into the python manage.py shell and do:

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

Another way that can give you more flexibility is to create a custom management team.

Here is a simple example:

 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 run it through the command line using python manage.py seed or python manage.py seed --users 50 , for example.

+5
source

Try this package:
https://github.com/gregmuellegger/django-autofixture

See also django packages, may possibly help with fake tests and other problems. https://www.djangopackages.com/grids/g/fixtures/

+2
source

Source: https://habr.com/ru/post/1233282/


All Articles