【问题标题】:Save method of Django model does not update fields of existing record even if force update即使强制更新,Django模型的保存方法也不会更新现有记录的字段
【发布时间】:2021-01-17 21:29:24
【问题描述】:

我正在尝试更新数据库中已存在的记录,因此我使用此代码

        if 'supplierId' not in req.keys():
            return JsonResponse({'code': 0, 'msg': "supplier was not selected", 'result': ''}, safe=False)

        assigneeId = User.objects.get(pk=req.get('assigneeId', 1))
        responsibleId = User.objects.get(pk=req.get('responsibleId', 1))
        redistributionMethod = req.get('redistributionMethod', 0)
        amount = req.get('allCost', 0)

        procurement_doc = ProcurementDocJournal.objects.get(id=pk)
        print(procurement_doc)
          procurement_doc.docType = req['docType']
        procurement_doc.status = req['status']
        procurement_doc.companyId = Company.objects.get(pk=req['companyId'])
        procurement_doc.datetime = req['datetime']
        procurement_doc.supplierId = Partner.objects.get(pk=req['supplierId'])
        procurement_doc.assigneeId = assigneeId
        procurement_doc.warehouseId = Warehouse.objects.get(pk=req['warehouseId'])
        procurement_doc.responsibleId = responsibleId
        procurement_doc.redistributionMethod = redistributionMethod
        procurement_doc.amount = amount
        procurement_doc.comment = req['comment']
        procurement_doc.save(force_update=True, update_fields=['comment', 'amount', 'redistributionMethod',
                                                               'responsibleId', 'warehouseId',
                                                               'supplierId', 'datetime',
                                                               'companyId', 'assigneeId', 'status', 'docType'])

req 包含一个请求 像这样的

{
    'docType': 3,
    'status': 1,
    'companyId': '2',
    'warehouseId': '3',
    'assigneeId': '5',
    'supplierId': '12671',
    'responsibleId': '5',
    'datetime': '2020-04-01 08:01:00',
    'comment': ''
}

如您所见,有一个打印件向我保证我选择了正确的行

当我注意到这些记录没有更新时,我搜索了原因并找到了

this 提问的人在哪里说 模型定义中缺少消息字段 就我而言,模型的描述中没有一个缺少这些

class ProcurementDocJournal(models.Model):
    id = models.IntegerField(primary_key=True, null=False)
    docNumber = models.IntegerField()
    status = models.IntegerField()
    docType = models.IntegerField()
    depended = models.IntegerField()
    companyId = models.ForeignKey(Company, on_delete=models.CASCADE,
                                  db_column='companyId')
    created_at = models.DateTimeField(auto_now_add=True)
    datetime = models.DateTimeField()
    currencyId = models.ForeignKey(Currency, db_column='currencyId', on_delete=models.CASCADE)
    currencyRate = models.FloatField()
    redistributionMethod = models.IntegerField()
    assigneeId = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ProcurementDocJournal',
                                   db_column='assigneeId')
    warehouseId = models.ForeignKey(Warehouse, on_delete=models.CASCADE,
                                    db_column='warehouseId')
    responsibleId = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ProcurementDoc',
                                      db_column='responsibleId')
    supplierId = models.ForeignKey(Partner, on_delete=models.CASCADE,
                                   db_column='supplierId')
    amount = models.FloatField()
    comment = models.TextField()

    class Meta:
        db_table = 'procurementDocJournal'
        get_latest_by = 'id'

编辑 我有一个包含

的动作
        procurement_doc_journal_item = ProcurementDocJournal.objects.get(id=pk)
        currencyId = req['currency']
        currency = Currency.objects.get(id=currencyId)
        currencyRate = CurrencyRate(date, currency.name)

        procurement_doc_journal_item.currencyId = currency
        procurement_doc_journal_item.currencyRate = currencyRate['rate']
        procurement_doc_journal_item.save()

并且像魅力一样工作

日志没有任何错误

【问题讨论】:

    标签: python-3.x django database django-models save


    【解决方案1】:

    您没有指定日志中是否有任何错误。我有点期待看到一些东西,因为如果它没有保存,它必须在此之前被轰炸,因为没有字段是强制性的。

    不过,我不确定您是否在此处正确设置了 FK:

    procurement_doc.companyId = Company(req['companyId'])
    

    应该是

    procurement_doc.companyId = Company.objects.get(pk=req['companyId'])
    

    并且假设companyId 设置为一个当然存在的值......这是否是您问题的根源,我不确定。我没有看到您的任何 FK 是强制性的。

    编辑:我刚刚用一个简单的id 键在我的一个模型上进行了测试:

    >>> Contact(1)
    Contact()
    >>> c = Contact(1)
    >>> c.name
    ''
    >>> c = Contact.objects.get(pk=1)
    >>> c.name
    'Mike'
    

    在我看来,它真的好像不起作用......

    旁注:您可以像这样简化代码:

        if 'allCost' not in req.keys():
            amount = 0
        else:
            amount = req['allCost']
    

    通过做:

    amount = req.get('allCost', 0)
    

    【讨论】:

    • 感谢您的建议,它不会返回任何错误。我将按照您的建议更换此员工,稍后再返回。关于provisioning_doc.companyId = Company(req['companyId']),在其他所有情况下,我在10K代码中都有类似的用途
    • 我刚刚在 django shell 中的一个项目上对此进行了测试。在我看来它似乎不起作用,所以不确定你在做什么而我不是?
    • 我已按照您的建议进行了编辑 c = Contact.objects.get(pk=1) 我的意思是这个,但没什么我还有另一段代码可以工作
    • 我相信你——只是不确定我们在做什么不同:) 我想这对你来说没有什么不同吗?也许在保存之前输出procurement_doc?我唯一的猜测是它认为没有数据发生变化,因此不会浪费数据库命中更新...
    • 我也这么认为,但几乎每次我也要求强制更新时数据都会发生变化,但什么都没有
    猜你喜欢
    • 2012-12-23
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多