gpt4 book ai didi

python - Django jsonfield 在循环中保留旧对象值

转载 作者:行者123 更新时间:2023-11-30 22:27:12 26 4
gpt4 key购买 nike

这是模型:

class ModelA(models.Model):
field1 = models.CharField(max_length=100)
field2 = models.CharField(max_length=100)
field3 = JSONField(default=[])

def save(self, *args, **kwargs):
# Below print should be None
# But it shows the value of the previously created object, why ?
print "------------------------------------------------"
print self.id
print "self.field3"
print self.field3
self.field2 = self.field1 + " world"
self.field3.append(self.field2)
super(ModelA, self).save(*args, **kwargs)

这是 View :

def view1(request):
for x in range(1, 3):
a = ModelA.objects.create(field1="hello%s" % x)

预期输出:

# None
# self.field3
# []

# None
# self.field3
# []

实现的输出:

# None
# self.field3
# []

# None
# self.field3
# [u'Hello1 world']

# None
# self.field3
# [u'Hello1 world', u'Hello2 world']

那么,根据给定的输出,你能告诉我为什么它在创建新对象时使用以前的对象值吗?

最佳答案

这是来自 Django documentation :

If you give the field a default, ensure it’s a callable such as dict (for an empty default) or a callable that returns a dict (such as a function). Incorrectly using default={} creates a mutable default that is shared between all instances of JSONField.

因此请使用它:

field3 = JSONField(default=list)

关于python - Django jsonfield 在循环中保留旧对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46986433/

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