OneToOneField关系未创建

时间:2014-11-02 03:45:08

标签: django django-forms

我有一个表单,在其中我从一些字段中获取数据并创建一个新的模型对象,然后将新创建的对象与一个不同模型的预先存在的对象分配一对一的关系。这是我在表单中的保存方法。

def save(self, *args, **kwargs):
    super(CustomerProfileForm, self).save(*args, **kwargs)
    if self.cleaned_data['street_address']:
        if not self.instance.customer.home_location:
            home_location = Location()
        else :
            home_location = self.instance.customer.home_location
        home_location.name = 'Home/Apartment'
        home_location.street_address = self.cleaned_data['street_address']
        home_location.city = self.cleaned_data['city']
        home_location.state = self.cleaned_data['state']
        home_location.zip_code = self.cleaned_data['zip_code']
        self.instance.customer.home_location = home_location
        home_location.save()
        self.instance.customer.save()

    return self.instance

正在创建Location对象并使用表单中的信息填充,但未分配与CustomerProfile对象(self.instance)的OneToOne关系。有谁知道为什么会这样?

这对我没有意义。当我在保存功能结束前打印self.instance.customer.home_location时,新位置将记录到控制台,这表明已分配关系...保存方法完成后如何取消分配...?

1 个答案:

答案 0 :(得分:1)

为了保存关系,对象需要有一个主键;这只是在保存对象后生成的。

因此,在将对象指定为外键之前,需要先保存对象:

    home_location.save()
    self.instance.customer.home_location = home_location
    # home_location.save() - this line should come before any relationships
    #                        are linked to the object.
    self.instance.customer.save()