2014-02-06 71 views
0

我試圖爲Django模型設置多個工廠,這些模型具有OneToOne關係&他們似乎不像外鍵那樣工作。使用OnetoOne關係爲Django模型創建工廠

當運行我的unittest主模型沒有它的關係設置。

我的模型:

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

+0

@danihp well spotted!我把它寫成'main','model1','model2',並意識到這是一個無聊的例子,因此在中途改變並錯過了那個!謝謝。 –

+0

這似乎是'ThePlanFactory'的問題,但是'OldPlanFactory'。你能告訴我們在哪裏(setUp的哪一行)引起錯誤? – danihp

回答

0

所以我的問題是關於時間和2個依賴工廠的創建。

而不是立即調用它們的創建,而是設置它們並在設置好​​關係後保存對象。以下工作是我需要的;

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