为什么span关系查询与get
一起工作而与create
不一起工作?有什么方法可以让它工作吗
一些背景:
目前我正在做类似的事情
qm = questionModel.object.get(question=quest)
answer = modelInterviewAnswer.objects.create(patient=patientobj,question=qm )
现在我知道这种方法已经奏效了
modelInterviewAnswer.objects.get(patient=patientobj,question__question=quest )
我的问题是,为什么这样的东西只对get
有效,而对create
无效
modelInterviewAnswer.objects.create(patient=patientobj,question__question=quest )
更新:
这是我尝试使用时遇到的错误
modelInterviewAnswer.objects.create(patient=patientobj,question__question=quest )
'question__question' is an invalid keyword argument for this function
所以我的问题是为什么question__question
与get一起工作,但是当我将它与create一起使用时,我会得到一个异常
嗯,你必须明确你所说的“它不起作用”是什么意思。从理论上讲,它确实可以工作——您确实可以通过调用
RandomClass.objects.create(field1='field-1-value', field2='field-2-value')
来创建对象,并且它可以工作。如果它对.get()
起作用,而对.create()
不起作用(我假设您在尝试该代码时遇到某种异常),那么一个原因可能是get()
从数据库中检索和现有对象,并可以从数据库中填充所有必需的字段值,当.create()
将一个新对象插入数据库时,如果缺少一些必需的值,则会出现异常。另一种方法或解决方案不是使用
create()
这基本上是一个直接的DB命令,而是使用Django中间模型实例来创建对象。基本上区别如下:如果你在寻找一个更具体的答案,相应地更新你的问题
编辑: 因为字段
question
位于另一个模型中,您不能使用一个模型的create()
方法更改另一个模型的字段。但是,您可以使用.get()
、.filter()
、.exclude()
等方法,根据现有对象的字段值筛选它们要实现你想要的,你必须做到以下几点(注意,这不是唯一的方法):
相关问题 更多 >
编程相关推荐