Hopefully this post helps you spin up a lot of fake data for your Django app very quickly. I use adorable.io for dummy profile pics and Picsum or Unsplash for larger pictures like this one. If you need dummy images for your website as well then there are a lot of great free tools online to help. Using the transaction.atomic decorator makes a big difference in the runtime of this script, since it bundles up 100s of queries and submits them in one go. choice ( people ) CommentFactory ( user = commentor, thread = thread ) choice ( people ) thread = ThreadFactory ( creator = creator ) # Create comments for each thread for _ in range ( COMMENTS_PER_THREAD ): commentor = random. add ( * members ) # Create all the threads for _ in range ( NUM_THREADS ): creator = random. choices ( people, k = USERS_PER_CLUB ) club. append ( person ) # Add some users to clubs for _ in range ( NUM_CLUBS ): club = ClubFactory () members = random. write ( "Creating new data." ) # Create all the users people = for _ in range ( NUM_USERS ): person = UserFactory () people. write ( "Deleting old data." ) models = for m in models : m. atomic def handle ( self, * args, ** kwargs ): self. # setup_test_data.py import random from django.db import transaction from import BaseCommand from forum.models import User, Thread, Club, Comment from forum.factories import ( UserFactory, ThreadFactory, ClubFactory, CommentFactory ) NUM_USERS = 50 NUM_CLUBS = 10 NUM_THREADS = 12 COMMENTS_PER_THREAD = 25 USERS_PER_CLUB = 8 class Command ( BaseCommand ): help = "Generates test data". For example, for a user, you would create a factory class as follows: When using Factory Boy you create classes called "factories", which each represent a Django model. Factory Boy can easily be configured to generate random but realistic data like names, emails and paragraphs by internally using the Faker library. It's a library that's built for automated testing, but it also works well for this use-case. We'll be using Factory Boy to generate all our dummy data. ManyToManyField ( User ) Building data with Factory Boy CharField ( max_length = 128 ) member = models. Model ): """A group of users interested in the same thing""" name = models. ForeignKey ( Thread ) class Club ( models. CharField ( max_length = 128 ) poster = models. Model ): """A comment by a user on a thread""" body = models. ForeignKey ( User ) class Comment ( models. CharField ( max_length = 128 ) creator = models. Model ): """A forum comment thread""" title = models. CharField ( max_length = 128 ) class Thread ( models. Model ): """A person who uses the website""" name = models.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |