Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

method to turn on auto_add and auto_add_now fields #111

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 22 additions & 10 deletions django_seed/seeder.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import random, logging
import random
import logging

from django.db.models import ForeignKey, ManyToManyField, OneToOneField

Expand Down Expand Up @@ -49,7 +50,8 @@ def func(inserted):
def build_many_relation(field, related_model):
def func(inserted):
if related_model in inserted and inserted[related_model]:
max_relations = min(10, round(len(inserted[related_model]) / 5) + 1)
max_relations = min(
10, round(len(inserted[related_model]) / 5) + 1)

return_list = []
for _ in range(random.randint(1, max_relations)):
Expand Down Expand Up @@ -111,7 +113,8 @@ def guess_field_formatters(self, faker, formatters=None):
continue

if isinstance(field, ForeignKey):
formatters[field_name] = self.build_relation(field, field.related_model)
formatters[field_name] = self.build_relation(
field, field.related_model)
continue

if not field.choices:
Expand Down Expand Up @@ -165,7 +168,6 @@ def turn_off_auto_add(model):

if field.max_length and isinstance(faker_data[data_field], str):
faker_data[data_field] = faker_data[data_field][: field.max_length]

obj = manager.create(**faker_data)

for field, list in self.many_relations.items():
Expand All @@ -185,6 +187,14 @@ def __init__(self, faker):
self.faker = faker
self.orders = []

@staticmethod
def turn_on_auto_add_fields(model):
for field in model._meta.fields:
if hasattr(field, 'auto_now'):
field.auto_now = True
if hasattr(field, 'auto_now_add'):
field.auto_now_add = True

def add_entity(self, model, number, customFieldFormatters=None):
"""
Add an order for the generation of $number records for $entity.
Expand Down Expand Up @@ -221,7 +231,6 @@ def execute(self, using=None, inserted_entities={}):
"""
if not using:
using = self.get_connection()

inserted_entities = {}
while len(self.orders):
order = self.orders.pop(0)
Expand All @@ -247,23 +256,26 @@ def execute(self, using=None, inserted_entities={}):
# This atomic transaction block guarentees that we can
# continue testing on an IntegrityError
with transaction.atomic():
executed_entity = entity.execute(using, inserted_entities)

executed_entity = entity.execute(
using, inserted_entities)

inserted_entities[klass].append(executed_entity)
completed_count += 1
except IntegrityError as err:
last_error = err

# Exit if the right number of entities has been inserted
if completed_count == number:
break

attempts -= 1

if completed_count == 0:
raise IntegrityError(f"Error: could not generate any instances of {klass.__name__}\nInternal error: {last_error}")
raise IntegrityError(
f"Error: could not generate any instances of {klass.__name__}\nInternal error: {last_error}")
elif completed_count != number:
print(f"Warning: could only generate {completed_count} out of {number} instances of {klass.__name__}, the rest errored with; {last_error}")
print(
f"Warning: could only generate {completed_count} out of {number} instances of {klass.__name__}, the rest errored with; {last_error}")

return inserted_entities

Expand Down
Loading