2013-10-14 176 views
0
first_obj = MyFirstModel() 
second_obj = ImageModel() 

first_obj.name = "newname" 
first_obj.phonenr = "9898876" 

second_obj.image = "new image" 

first_obj.save() 

first_obj.create(second_obj) #<------ can i do this? 

這會保存第二個對象嗎?是否有可能做到這一點?我可以在Django中以這種方式保存模型嗎?

+0

你想做什麼?您是否試圖將外鍵參考表格保存爲第一個到第二個? –

+0

@ TimmyO'Mahony,我試圖通過第一個對象來保存第二個對象。他們是有關係的。 YES對你的評論 – doniyor

+0

@ TimmyO'Mahony,有一個創建函數會創建和保存相關的對象,對嗎? – doniyor

回答

1

我覺得你越來越糊塗了,試試這個:

class ImageModel(models.Model): 
    image = models.ImageField() 

class MyFirstModel(models.Model): 
    name = ... 
    image = models.ForeignKey(Image) 


> image_model_instance = ImageModel() 
> image_model_instance.save() 
> first_model_instance = MyFirstModel(name="foo") 
> first_model_instance.image = image_model_instance 
> first_model_instance.save() 

有一個create() function,但它是用於創建和保存模型的新實例:

first_model_instance = MyFirstModel.objects.create(Name="foo") 

所以同樣作爲:

first_model_instance = MyFirstModel() 
first_model_instance.save() 
+0

謝謝,看起來很好 – doniyor

相關問題