我正在尝试使用 factory_boy 为这些模型制作工厂:
class Course(models.Model):
group = models.OneToOneField(Group)
title = models.CharField(max_length=1024)
class CourseInfo(models.Model):
course = models.OneToOneField(Course, related_name='info')
starttime = models.TimeField(null=True, blank=True)
endtime = models.TimeField(null=True, blank=True)
这是我的工厂:
class CourseInfoFactory(factory.DjangoModelFactory):
class Meta:
model = CourseInfo
course = factory.SubFactory('courseaffils.tests.factories.CourseFactory')
starttime = time(hour=4)
endtime = time(hour=6)
class CourseFactory(factory.DjangoModelFactory):
class Meta:
model = Course
title = factory.Sequence(lambda n: 'Example Course %d' % n)
group = factory.SubFactory(GroupFactory)
info = factory.RelatedFactory(CourseInfoFactory, 'course')
现在,当我打电话CourseFactory()
或CourseInfoFactory()
收到 IntegrityError 时:
IntegrityError:唯一约束失败:courseaffils_courseinfo.course_id
我的工厂出了什么问题?我该如何解决这个问题?
如果我改为course = factory.RelatedFactory('courseaffils.tests.factories.CourseFactory')
在 CourseInfoFactory 上执行,我会收到此错误,如预期的那样:
IntegrityError:NOT NULL 约束失败:courseaffils_courseinfo.course_id
如果您需要更多详细信息,这是我正在使用的实际代码:
https://github.com/ccnmtl/django_courseaffils/blob/master/courseaffils/models.py