我正在尝试为具有 OneToOne 关系的 Django 模型设置许多工厂,并且它们的行为方式似乎与外键不同。
运行我的单元测试时,主模型没有设置它的关系。
我的模型:
class ThePlan(models.Model):
user = models.ForeignKey("User")
creationdate = models.DateField(auto_now_add=True)
class OldPlan(models.Model):
plan = models.OneToOneField("ThePlan")
theplan = CharField(max_length = 200,)
class NewPlan(models.Model):
plan = models.OneToOneField("ThePlan")
theplan = CharField(max_length = 200,)
我的工厂:
class ThePlanFactory(factory.DjangoModelFactory):
FACTORY_FOR = "mysite.PlanModel"
user = factory.SubFactory(UserFactory)
class OldPlanFactory(factory.DjangoModelFactory):
FACTORY_FOR = "mysite.OldModel"
plan = factory.RelatedFactory(ThePlanFactory)
theplan = ''
class NewPlanFactory(factory.DjangoModelFactory):
FACTORY_FOR = "mysite.NewModel"
plan = factory.RelatedFactory(ThePlanFactory)
theplan = ''
在我的测试中,setUp()
我正在执行以下操作;
def setUp(self):
self.user = factories.UserFactory.create()
self.plan = factories.ThePlanFactory.create(
user=self.user
)
self.oldplan = factories.OldPlanFactory.create(
plan=self.plan
)
self.newplan = factories.NewPlanFactory.create(
plan=self.plan
)
因此,当我运行包含此内容的测试时,我得到了DoesNotExist: ThePlan has no OldPlan
.
我在哪里错了?是我create
立即打电话的问题,而是我应该设置工厂build
,设置关系,然后打电话save
?