我的模型如下:
class Question(models.Model):
content = models.CharField(
max_length=1000,
blank=False,
default='',
)
def __str__(self):
return self.content
class OptionGroup(models.Model):
question = models.ForeignKey(
'Question',
on_delete=models.CASCADE,
default='',
)
options = models.ManyToManyField('Option')
class Option(models.Model):
content = models.CharField(
max_length=1000,
blank=False,
default='',
)
我的工厂如下:
class QuestionFactory(factory.django.DjangoModelFactory):
class Meta:
model = Question
content = factory.Sequence(lambda n: 'Question %d' % n)
class OptionGroupFactory(factory.django.DjangoModelFactory):
class Meta:
model = OptionGroup
question = factory.SubFactory(QuestionFactory)
@factory.post_generation
def options(self, create, extracted, **kwargs):
if not create:
return
if extracted:
for option in extracted:
self.options.add(option)
class OptionFactory(factory.django.DjangoModelFactory):
class Meta:
model = Option
content = factory.Sequence(lambda n: 'Option %d' % n)
现在,为了易于使用,我想创建一个Question工厂类,该类创建两个具有两个Option对象的OptionGroup对象。为了做到这一点,我正在使用这个工厂,但是它不起作用:
class QWith2OptGrps4Options(QuestionFactory):
option_group1 = factory.RelatedFactory(
OptionGroupFactory,
'question',
options=(OptionFactory.create(), OptionFactory.create())
)
option_group2 = factory.RelatedFactory(
OptionGroupFactory,
'question',
options=(OptionFactory.create(), OptionFactory.create())
)
我认为它必须与声明OptionFactory的方式有关,但是我不知道如何正确地进行操作。有帮助吗?