4

我有一个带有 JSONField 的模型(仅限 Postgres 字段):

模型.py:

from django.db import models
from django.contrib.postgres.fields import JSONField

class Mod(models.Model):
    data = JSONField(default={ 'name':'Model' })

所以我创建了 2 个模型 - <code>./manage.py shell:

>>> from m3d.models import Mod
>>> m1 = Mod()
>>> m1.save()
>>> m2 = Mod()
>>> m2.data['name'] = 'Model 2'
>>> m2.save()

但它们具有相同的data['name']值:

>>> m1.data['name']
'Model 2'
>>> m2.data['name']
'Model 2'

请注意,数据库中的值不同

>>> m1a = Mod.objects.get(pk=m1.pk) # get m1 data from db
>>> m1a.data['name']
'Model'
>>> m2.data['name']
'Model 2'

但变量m1仍然具有值Model 2

我错过了什么吗?这是我需要解决的某种行为吗?

仅供参考:使用 Django 2.0.1

4

1 回答 1

15

This is covered in the documentation. The way you are setting the default for your field is incorrect:

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.

This is the behaviour that you are seeing, where the same object is shared between the instances that you have created, and modifying one results in the other also being changed.

You need to use a callable instead, e.g., :

def get_default_data():
    return { 'name':'Model' }

class Mod(models.Model):
    data = JSONField(default=get_default_data)
于 2018-01-07T03:19:02.540 回答