post_generation 钩子怎么样- 我假设您使用较新版本的factory_boy?
import random
import factory
class PostFactory(factory.Factory):
FACTORY_FOR = Post
title = factory.Sequence(lambda n: "This is test title number" + n)
@factory.post_generation(extract_prefix='tags')
def add_tags(self, create, extracted, **kwargs):
# allow something like PostFactory(tags = Tag.objects.filter())
if extracted and type(extracted) == type(Tag.objects.all()):
self.tags = extracted
self.save()
else:
if Tag.objects.all().count() < 5:
TagFactory.create_batch(5, **kwargs)
for tag in Tag.objects.all().order_by('?')[:random.randint(1, 5)]:
self.tags.add(tag)
请注意,您可以使用PostFactory(tags__field = 'some fancy default text')
,但我建议使用 Sequences 创建好的TagFactory
...
您应该可以绑定PostFactory(tags = Tag.objects.filter())
,但这部分未经测试...