我的表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
对象。我做错了什么?
答案 0 :(得分:1)
不,分配*_id
字段不会加载相应的模型实例。所以你应该手动加载实例:
project.save()
project.sales_person = MyUser.objects.get(pk=project.sales_person_id)
但是为什么你没有为该字段分配MyUser
个实例?这不会增加任何性能损失:
project.sales_person = project.customer.created_by