gpt4 book ai didi

python - 更新django中外键模型的数据

转载 作者:行者123 更新时间:2023-11-29 09:50:50 26 4
gpt4 key购买 nike

我有两个模型

class LabReportRelation(models.Model):
labReportId = models.AutoField(primary_key=True)
collectedSampleId = models.ForeignKey(CollectedSample, null=True)
....
....
class Meta:
db_table = 'labReportRelation'

class CollectedSample(models.Model):
id = models.AutoField(primary_key=True, max_length=5)
collectionTime = models.DateTimeField()
....
....
class Meta:
db_table = 'collectedSample'

我想更新与“labereportId”相关的 CollectedSample 模型的“collectionTime”

我当前的查询是:

LabReportRelation.objects.filter(labReportId__in=labReportIdList)
.prefetch_related('collectedSampleId')
.update(
collectedSampleId_collectionTime=updateTime
)

但我收到此错误。

FieldDoesNotExist(u"labReportRelation has no field named 'collectedSampleId_collectionTime'",)

请帮助我。

最佳答案

以下作品:

CollectedSample.objects.filter(labreportrelation__labReportId__in=labReportIdList).update(collectionTime=updateTime)

假设labReportIdList是一个列表。

运行以下命令(模型与OP中的完全相同):

import os

_module = os.path.split(os.path.dirname(__file__))[-1]
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{}.settings".format(_module))
import django

django.setup()
from app.models import CollectedSample, LabReportRelation
from django.utils.timezone import now


if __name__ == "__main__":
sample = CollectedSample.objects.create(collectionTime=now())
report = LabReportRelation.objects.create(collectedSampleId=sample)
print(f"Initial collection time: {sample.collectionTime} for sample {sample.id}")
labReportIdList = [report.labReportId]
updateTime = now()
CollectedSample.objects.filter(labreportrelation__labReportId__in=labReportIdList).update(collectionTime=updateTime)
sample = CollectedSample.objects.get(pk=sample.pk)
print(f"Updated collection time: {sample.collectionTime} for sample {sample.id}")

打印:

Initial collection time: 2019-02-23 07:51:10.578433+00:00 for sample 3
Updated collection time: 2019-02-23 07:51:10.735463+00:00 for sample 3

它向后遵循ForeignKey关系,如官方文档here中所述。

关于python - 更新django中外键模型的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54839066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com