1

我正在尝试为具有 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

4

1 回答 1

1

所以我的问题与时间和 2 个依赖工厂的创建有关。

我没有立即对它们调用 create ,而是设置它们并plan在设置关系后保存对象。以下是我需要的工作;

def setUp(self):
    self.user = factories.UserFactory.create()

    self.plan = factories.ThePlanFactory.create(
        user=self.user
    )
    self.oldplan = factories.OldPlanFactory()
    self.oldplan.plan = self.plan
    self.oldplan.save()

    self.newplan = factories.NewPlanFactory()
    self.newplan.plan = self.plan
    self.newplan.save()
于 2014-02-06T13:12:26.377 回答