无法将新值分配给Django模型字段

2024-09-29 23:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个calculation = models.FloatField(default=0)字段,我正试图将新值(根据Debugger its 32)分配给它,如下所示:

   def calculate(**kwargs):
       row = ContractorScoring.objects.select_related('client', 'lead', 'budgetOptions', 'techCompatibility',
                                               'availableMen', 'degreeOfElaboration', 'geography',
                                               'nonInHouseReady', 'existingItPartner', 'httpsAvailability',
                                               'monthlyAdsBudget', 'mobilePageLoadSpeed', 'desktopPageLoadSpeed',
                                               'organicTraficTrend', 'payedTraficTrend', 'techStackEquality',
                                               'projectType', 'customerReadiness', 'servicesMeet')

       points_sum = float(row[0].budgetOptions.points + row[0].techCompatibility.points +
                   row[0].availableMen.points + row[0].degreeOfElaboration.points +
                   row[0].geography.points + row[0].nonInHouseReady.points +
                   row[0].existingItPartner.points + row[0].httpsAvailability.points +
                   row[0].monthlyAdsBudget.points + row[0].mobilePageLoadSpeed.points +
                   row[0].desktopPageLoadSpeed.points + row[0].organicTraficTrend.points +
                   row[0].payedTraficTrend.points + row[0].techStackEquality.points +
                   row[0].projectType.points + row[0].customerReadiness.points + row[0].servicesMeet.points)

       row[0].calculation = points_sum
       print(str(row[0].calculation))
       row[0].save(update_fields=['calculation'])

       return row[0].calculation

当我打印row[0].calculation值时,它会给我默认值0,0

你知道我做错了什么吗


Tags: pointsrowcalculationgeographyavailablemendesktoppageloadspeedbudgetoptionsdegreeofelaboration
1条回答
网友
1楼 · 发布于 2024-09-29 23:22:22

您不应该修改仍在查询集中的模型实例(row[0],其中row有点用词不当)

而是抓住对象本身:

def calculate(**kwargs):
    scoring = ContractorScoring.objects.select_related(...).first()
    points_sum = float(scoring.a + scoring.b + ...)
    scoring.calculation = points_sum
    scoring.save(update_fields=["calculation"])
    return scoring.calculation

请注意,您在ContractorScoring查询中缺少任何类型的过滤器,因此根本无法保证您将获得各种ContractorCoring的哪个对象!那可能不是你想要的

相关问题 更多 >

    热门问题