【问题标题】:Python how to iterate from an array of objects and use key values to update multiple records at oncePython如何从对象数组中迭代并使用键值一次更新多条记录
【发布时间】:2019-03-21 04:03:44
【问题描述】:

Python 如何从对象数组中迭代并使用键值一次更新多条记录。我想 更新表中的多行,其中 companyid = 公司和申请人 ID = 申请人,因为您可以在 json 中看到公司和申请人值,并根据任务 ID 设置 attach_document_ins.is_viewed 等于检查的值。 https://imgur.com/a/nttq6XT(表格行)

代码

def post(self, request):
    data = request.data
    print("Response Data :" , data)
    try:

         for item in data['tasklist']:
            company = item['company']
            applicant = item['applicant']
            hey = item['checked']

        attached_document_ins = DocumentTask.objects.filter(company=company , applicant = applicant)
        for attached_document_ins in attached_document_ins:
            attached_document_ins.is_viewed = True
        attached_document_ins.save()
        return Response("Success", status=status.HTTP_200_OK)
    except DocumentTask.DoesNotExist:
        return Response("Failed.", status=status.HTTP_400_BAD_REQUEST)

数据

{
   'tasklist':[
        {
            'company':6,
            'checked':True,
            'files':[

            ],
            'applicant':159,
            'id':35,
            'task':'s'
        },
        {
            'company':6,
            'checked':True,
            'files':[

            ],
            'applicant':159,
            'id':36,
            'task':'ss'
        },
        {
            'company':6,
            'checked':True,
            'files':[

            ],
            'applicant':159,
            'id':37,
            'task':'sss'
      }
   ]
}

【问题讨论】:

  • 您要更新哪些字段?在什么条件下?

标签: python django python-3.x loops iteration


【解决方案1】:

你可以通过 queryset.update 更新多行

DocumentTask.objects.filter(company=company , applicant = applicant).update(is_viewed=True)

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 2021-09-22
    • 1970-01-01
    • 2021-12-07
    • 2015-01-13
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多