如何在Django和django-jsonfield中将JSONField的默认值设置为空列表?

时间:2021-08-26 20:01:34

Question

What is the best way to set a JSONField to have the default value of a new list in django?

在django中将JSONField设置为具有新列表的默认值的最佳方法是什么?

Context

There is a model where one of the fields is a list of items. In the case where there are no items set, the model should have an empty list.

有一个模型,其中一个字段是项目列表。在没有设置项目的情况下,模型应该有一个空列表。

Current solution

from django.models import Model

class MyModel(Model):
    the_list_field = JSONField(default=[])

Is this the best way to do it? Should it be switched to use list instead?

这是最好的方法吗?是否应该切换到使用列表?

Thanks!

谢谢!

1 个解决方案

#1


16  

According to the Django documentation for JSONField you should indeed use default=list because using default=[] would create a mutable object that is shared between all instances of your field and could lead to some objects not having an empty list as a default.

根据JSONField的Django文档,您确实应该使用default = list,因为使用default = []会创建一个可变对象,该对象在您的字段的所有实例之间共享,并且可能导致某些对象没有空列表作为默认值。

Please note that this does not only apply for django.contrib.postgres.fields.JSONField but for all other kinds of objects and functions in Python in general.

请注意,这不仅适用于django.contrib.postgres.fields.JSONField,而且适用于Python中的所有其他类型的对象和函数。

Quote from the docs:

从文档引用:

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

如果为该字段指定默认值,请确保它是可调用的,例如list(对于空的默认值)或可调用的返回列表(例如函数)。错误地使用default = []会创建一个在所有实例之间共享的可变默认值

#1


16  

According to the Django documentation for JSONField you should indeed use default=list because using default=[] would create a mutable object that is shared between all instances of your field and could lead to some objects not having an empty list as a default.

根据JSONField的Django文档,您确实应该使用default = list,因为使用default = []会创建一个可变对象,该对象在您的字段的所有实例之间共享,并且可能导致某些对象没有空列表作为默认值。

Please note that this does not only apply for django.contrib.postgres.fields.JSONField but for all other kinds of objects and functions in Python in general.

请注意,这不仅适用于django.contrib.postgres.fields.JSONField,而且适用于Python中的所有其他类型的对象和函数。

Quote from the docs:

从文档引用:

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

如果为该字段指定默认值,请确保它是可调用的,例如list(对于空的默认值)或可调用的返回列表(例如函数)。错误地使用default = []会创建一个在所有实例之间共享的可变默认值