在Django中更新伪造密钥模型的数据

时间:2019-02-23 06:55:34

标签: python mysql django django-models orm

我有两个模型

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'",)

请帮助我。

2 个答案:

答案 0 :(得分:1)

以下作品:

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

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

答案 1 :(得分:0)

哦,它被收集了SampleId是外键,所以您应该使用select_related

LabReportRelation.objects.filter(labReportId__in=labReportIdList)
     .select_related('collectedSampleId')
     .update(
        collectedSampleId__collectionTime=updateTime
     )