Django JSONField不保存0值

问题描述 投票:5回答:1

我在我的模型中有一个JSONField,当我尝试在django管理页面中的json中保存0作为值时,它将值保存为null。如何将零值保存? Django版本:2.1.7

Django管理页面:

enter image description here

我的JSONField:

lecturer_scores = JSONField(
        verbose_name=_("Lecturer Score"),
        validators=[validate_lecturer_score],
        default=dict,
        blank=True
    )

我的意见:

{
"score 1": 0,
"score 2": 5
}

它节省如下:

{
"score 1": null,
"score 2": 5
}

验证器:

from django.core.validators import validate_integer
from django.core.exceptions import ValidationError

def validate_lecturer_score(value):
    for k, v in value.items():
        if v:
            validate_integer(v)
    for value in value.values():
        if value:
            if value < 0 or value > 100:
                raise ValidationError(_("Lecturer score for user's participance rate calculation should be between 0 and 100."))
python django postgresql model django-jsonfield
1个回答
1
投票

问题在我的信号中,我调用属性方法并设置值。我检查值是否为空将其设置为null。像这样的lecturer_scores[key] = self.lecturer_scores.get(key) or None

© www.soinside.com 2019 - 2024. All rights reserved.