gpt4 book ai didi

python - 在 django 中为模型编写自定义更新方法

转载 作者:行者123 更新时间:2023-12-01 08:51:00 25 4
gpt4 key购买 nike

我想为我的模型编写一个自定义更新方法。基本上我想确保传递给此方法的字段是此模型中存在的字段。我想出了这样的东西

def update(self,dict):
#Check if the fields in this data are present in this model
for key in data:
if not hasattr(self, key):
#This property is not present
data.pop(key)
self.update(data)

但是当我做这样的事情时

modelMyobject.objects.filter(xxxxx).update(**dict)

这个方法永远不会被调用。有什么建议可以解决这个问题吗?

最佳答案

您正在 Querysets 中运行模型方法,因此请尝试以下任一方法:

for i in modelMyobject.objects.filter(xxxxx):
i.update(**dict)

或者写Custom Django Model Manager .

关于python - 在 django 中为模型编写自定义更新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53126235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com