Skip to content

Commit f51fa6d

Browse files
committed
Merge pull request #23 from ar45/fix_func_closure
Fixed use of outer vars in function build_relation
2 parents d37bbb7 + aa99fe4 commit f51fa6d

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

django_seed/seeder.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,17 @@ def __init__(self, model):
1414
self.model = model
1515
self.field_formatters = {}
1616

17+
@staticmethod
18+
def build_relation(field, related_model):
19+
def func(inserted):
20+
if related_model in inserted and inserted[related_model]:
21+
pk = random.choice(inserted[related_model])
22+
return related_model.objects.get(pk=pk)
23+
else:
24+
message = 'Field {} cannot be null'.format(field)
25+
raise SeederException(message)
26+
return func
27+
1728
def guess_field_formatters(self, faker):
1829
"""
1930
Gets the formatter methods for each field using the guessers
@@ -28,17 +39,7 @@ def guess_field_formatters(self, faker):
2839
for field in model._meta.fields:
2940
field_name = field.name
3041
if isinstance(field, (ForeignKey, ManyToManyField, OneToOneField)):
31-
related_model = field.rel.to
32-
33-
def build_relation(inserted):
34-
if related_model in inserted and inserted[related_model]:
35-
pk = random.choice(inserted[related_model])
36-
return related_model.objects.get(pk=pk)
37-
else:
38-
message = 'Field {} cannot be null'.format(field)
39-
raise SeederException(message)
40-
41-
formatters[field_name] = build_relation
42+
formatters[field_name] = self.build_relation(field, field.rel.to)
4243
continue
4344

4445
if isinstance(field, AutoField):

0 commit comments

Comments
 (0)