使用类跨度格式创建对象。可能吗?

2024-09-22 16:36:21 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么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一起使用时,我会得到一个异常


Tags: 方法getobjects关系create事情spanquestion
1条回答
网友
1楼 · 发布于 2024-09-22 16:36:21

嗯,你必须明确你所说的“它不起作用”是什么意思。从理论上讲,它确实可以工作——您确实可以通过调用RandomClass.objects.create(field1='field-1-value', field2='field-2-value')来创建对象,并且它可以工作。如果它对.get()起作用,而对.create()不起作用(我假设您在尝试该代码时遇到某种异常),那么一个原因可能是get()从数据库中检索和现有对象,并可以从数据库中填充所有必需的字段值,当.create()将一个新对象插入数据库时,如果缺少一些必需的值,则会出现异常。
另一种方法或解决方案不是使用create()这基本上是一个直接的DB命令,而是使用Django中间模型实例来创建对象。基本上区别如下:

from django.db import models

class RandomModel(models.Model):
    # NB! Required fields
    field1 = models.CharField(max_length=32)
    field2 = models.CharField(max_length=32)


# This is how you want to do it
RandomModel.objects.create(field1='value')
# An error is returned because you didn't specify a value for field2 and this goes directly to DB

# An alternative:
obj = RandomModel(field1='value')
obj.field2 = 'value232'
obj.save() #  Only here is it saved to the DB

如果你在寻找一个更具体的答案,相应地更新你的问题

编辑: 因为字段question位于另一个模型中,您不能使用一个模型的create()方法更改另一个模型的字段。但是,您可以使用.get().filter().exclude()等方法,根据现有对象的字段值筛选它们

要实现你想要的,你必须做到以下几点(注意,这不是唯一的方法):

# if the question instance exists and you just want to change the question (kind of unlikely in my opinion?)
question_instance = QuestionModel.objects.get(#some-params-that-get-the-question)
question_instance.question = 'How the hell did we end up here?'
question_instance = question_instance.save()
# Proceed to create the other model

# if the question instance does not exist (more likely version)
question = QuestionModel.objects.create(question='Is this more like it?')
answer = AnswerModel.objects.create(answer='Yes, it is.', question=question)

相关问题 更多 >