【问题标题】:Not getting ForeignKey value after Model.Form.save在 Model.Form.save 之后没有得到 ForeignKey 值
【发布时间】:2015-02-10 10:28:14
【问题描述】:

我的表中有以下属性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 对象。我没有做错什么?

【问题讨论】:

    标签: python django orm foreign-keys


    【解决方案1】:

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

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

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

    project.sales_person = project.customer.created_by
    

    【讨论】:

    • 第二个选项更有意义。但不确定为什么不保存实例后;到模型,我们可以通过查询数据库来访问那个推销员实例,但是当前的模型对象没有反映变化。奇怪
    • 这并不奇怪。当您操作*_id 字段时,您故意绕过处理实例的ForeignKey 属性的django 代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多