Django,如何在CreateView中手动创建对象

时间:2015-11-04 13:00:44

标签: django

我有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)

1 个答案:

答案 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