在Model.Form.save之后没有得到ForeignKey值

时间:2015-02-10 10:28:15

标签: python django orm foreign-keys

我的表Project

中有以下属性
sales_person = models.ForeignKey(MyUser, related_name='ad_sales_person', editable=False,null=True, blank=True)

我有这样的模型表单。

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
 exclude = ('created_by', 'current_user', 'project_current_state')


 def save(self, request=None, commit=False):
        project = super(ProjectForm, self).save(commit=commit)
        project.sales_person_id = project.customer.created_by.id
        project.save()
        project.sales_person # I should get the User object here. But i am not getting it here? 

我希望在保存模型对象后获取sales_person对象。我做错了什么?

1 个答案:

答案 0 :(得分:1)

不,分配*_id字段不会加载相应的模型实例。所以你应该手动加载实例:

project.save()
project.sales_person = MyUser.objects.get(pk=project.sales_person_id)

但是为什么你没有为该字段分配MyUser个实例?这不会增加任何性能损失:

project.sales_person = project.customer.created_by