我正在尝试使用创建 JSON 模型字段的副本.copy()
,但是我对副本所做的任何更改仍然反映在我不想要的数据库中。我可以迭代模型字段并创建一个新字典,但我认为有一种更Pythonic的方式。
模型.py
Class User(models.model):
settings = models.JSONField(default=dict(color = "Yellow", shape = "Square"))
Run Code Online (Sandbox Code Playgroud)
视图.py
...
user = User.objects.get(id=1)
settings = user.settings
settings_copy = user.settings.copy()
#settings model field is being changed here despite being a copy
settings_copy['color'] = Blue
...
Run Code Online (Sandbox Code Playgroud)
您基本上使用的dict.copy
是字典的浅表副本,即内部对象引用原始对象引用的同一实例。尝试使用copy.deepcopy
:
import copy
...
user = User.objects.get(id=1)
settings = user.settings
settings_copy = copy.deepcopy(settings)
settings_copy['color'] = Blue
...
Run Code Online (Sandbox Code Playgroud)