- integrate faker library - write script to populate fake data for testingmain
parent
8155f3c8c4
commit
b7431e26fc
@ -0,0 +1,54 @@
|
||||
def populate():
|
||||
from polls.models import Poll, Option
|
||||
|
||||
from random import randint
|
||||
|
||||
from faker import Faker
|
||||
|
||||
data_maker = Faker()
|
||||
|
||||
number_of_polls = 100
|
||||
options_per_poll = (2, 5)
|
||||
|
||||
for i in range(number_of_polls):
|
||||
poll = Poll()
|
||||
question = data_maker.sentence()
|
||||
question.replace(".", "?")
|
||||
poll.question = question
|
||||
poll.save()
|
||||
|
||||
for o in range(randint(*options_per_poll)):
|
||||
option = Option()
|
||||
option.poll = poll
|
||||
option.text = data_maker.sentence()
|
||||
option.save()
|
||||
|
||||
|
||||
def create_users_and_votes():
|
||||
from django.contrib.auth.models import User
|
||||
from polls.models import Poll, Option, Vote
|
||||
|
||||
from random import choice, shuffle
|
||||
|
||||
from faker import Faker
|
||||
|
||||
data_maker = Faker()
|
||||
|
||||
users_to_create = 16
|
||||
for i in range(users_to_create):
|
||||
user = User.objects.create_user(
|
||||
data_maker.unique.name(),
|
||||
)
|
||||
polls = list(Poll.objects.values_list("pk", flat=True))
|
||||
# Shuffle polls list
|
||||
shuffle(polls)
|
||||
# Vote on 75% of the polls
|
||||
for o in range(int(len(polls) * 0.75)):
|
||||
poll = Poll.objects.get(pk=polls[o])
|
||||
# Select a random option to cast as vote
|
||||
option_id = choice(Option.objects.filter(poll=poll).values_list("pk", flat=True))
|
||||
vote = Vote()
|
||||
vote.poll = poll
|
||||
vote.option = Option.objects.get(pk=option_id)
|
||||
vote.user = user
|
||||
vote.save()
|
Loading…
Reference in new issue