gpt4 book ai didi

django - auto_now 字段未使用 filter() 进行更新

转载 作者:行者123 更新时间:2023-12-01 22:05:46 26 4
gpt4 key购买 nike

我正在使用 Django 2.0

我有一个像这样的模型

class MyModel(models.Model):
update_new = models.CharField(blank=True, max_length=200)
modified = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)

并使用 Model Manager 更新模型数据

class MyModelManager(models.Manager):
def get_queryset(self):
return MyModelQueryset(self.model, self._db)

def update_or_create(self, pk, **save_data):

record = MyModel.objects.filter(
pk=pk
)

if record.exists():

# setting field manually for testing
save_data['update_new'] = 'anuj'

uc = record.update(**save_data)
print(uc) # prints 1

return record.first(), True

record, created = self.get_queryset().get_or_create(
pk=pk
**save_data
)

return record, created

这工作正常并且值已更新。但是 modified 字段没有更新。 createdmodified 字段中的值保持不变(记录创建时的时间戳)

最佳答案

docs 中描述了这种行为:

The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.

关于django - auto_now 字段未使用 filter() 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52159958/

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