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

标签 python django django-models filter

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

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/

相关文章:

python - Elasticsearch,如何每天每小时获取订单

android - 如何使用 Appium 在真实设备上从 jenkins 安装 *.apk 并运行用 python 编写的测试?

Python 程序共存于 Windows

python - 如何停止 TastyPie 无缘无故地执行更新查询?

django - 从模型表单集 django 中动态删除表单

python - 使用 pyodbc 时 SQL 查询失败,但在 SQL 中有效

django - Heroku Django 应用程序静态文件未提供服务(错误 OSError : [Errno 2])

python - 使用具有外键关系的两个模型通过共享文本标签使用 QuerySet API 对 django 对象进行分组

python - 指示小时较小的 TimeField 的最佳方法是 'after' 小时较大的 TimeField

python - 日期范围内的 Django 聚合