我有CreateView
创建Model1对象。我需要创建其他对象(在此视图中),它将Model1作为ForeignKey。
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)
答案 0 :(得分: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