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

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

请帮助我。

最佳答案

以下作品:

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/

相关文章:

python - 值错误 ("Incomplete wav chunk.") 值错误 : Incomplete wav chunk

python - 计算数据框中列的每一行中数组的每个唯一数组

php - 在特定条件下从 3 个相关表中获取数据的 mysql 查询逻辑

Django 模板 : How to show the time differences between a Datastore time and current time?

python - (Python 2.7)使用访问器/更改器(mutator)从类访问变量

python - 只读取大型 JSON 中的特定字段并导入 Pandas Dataframe

mysql:查看给定数据库的所有打开连接?

php - 关联数组中最常见的值

python - celery 自动重新加载不起作用

python - 无法让 Django 管理员在 Apache 上查找静态文件(css、img、js)