質問

I'm trying to setup a number of factories for Django models which have a OneToOne relationship & they don't seem to behave in the same way as foreign keys.

When running my unittest the main model doesn't have it's relationships set.

My models:

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,)

My factories:

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 = ''

And in my test setUp() I'm doing the following;

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
    )

So when I'm running a test with this included I'm getting DoesNotExist: ThePlan has no OldPlan.

Where am I going wrong here? Is the problem that I'm calling create immediately and instead I should setup the factories with build, set the relationships, and then call save?

役に立ちましたか?

解決

So my issue was related to time and the creation of the 2 dependant factories.

Instead of calling create on them straight away, I instead set them up and saved the objects once the plan relationship had been set. The following works as I need it to;

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()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top