2015-11-04 63 views
0

我有一個CreateView,它創建了Model1對象。我需要創建其他對象(在此視圖中),將Model1作爲ForeignKey。Django,如何在CreateView中創建對象,手動

from .models import Model1, Model2 

class Creating(CreateView): 
    model = Model1 
    fields = ["field"] 

    def form_valid(self, form): 
     # how to create here something like this: 
     # model2 = Model2.create(field_from_model2 = Model1_object_which_was_created_in_this_View?) 
     return super(Upload, self).form_valid(form) 

回答

2

super()被稱爲該CreateView,對象被保存爲self.object。您可以撥打super(),但不返回響應。然後,您可以使用self.object創建第二個對象。最後,返回響應。

class Creating(CreateView): 
    model = Model1 
    fields = ["field"] 

    def form_valid(self, form): 
     response = super(Creating, self).form_valid(form) 
     object2 = Model2.objects.create(
      model1=self.object, 
      # other fields 
     ) 
     return response 
相關問題