python - Model.Form.save 后未获取外键值

标签 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 对象。我没有做错什么?

最佳答案

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

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

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

project.sales_person = project.customer.created_by

关于python - Model.Form.save 后未获取外键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28429358/

相关文章:

python - Cherrypy 与 Mysql 错误 : "tuple indices must be integers, not str" when trying to add users

linux - "python: can' t 打开文件 'manage.py' : [Errno 2] No such file or directory"when running tmux shell script?

.net - N 层 POCO/DTO 困境

java - 将数据集加载到数据库时来自 DBUnit 的 NoPrimaryKeyException

python - "Regrouping"来自嵌套字典的数据

Python:如何在距离以米为单位的点周围创建方形缓冲区

python - 从 Python 中的元组列表中迭代查找/替换

python - 难以使用 Python 在未预授权的主机上实现 ping/延迟功能

java - Hibernate vs JPA vs JDO - 各自的优缺点?

python - getattr 错误