Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django JSONField does not save 0 value

I have a JSONField in my model, when I try to save 0 as value in json in django admin page, it saves value as null. How can I save zero as value? Django version: 2.1.7

Django admin page:

enter image description here

my JSONField:

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

My input:

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

it saves like:

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

Validator:

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."))
like image 204
Ali Soltani Avatar asked Nov 06 '22 18:11

Ali Soltani


1 Answers

issue was in my signal, I call a property method and set the values. I check if value is empty set it as null. something like this lecturer_scores[key] = self.lecturer_scores.get(key) or None

like image 79
Ali Soltani Avatar answered Nov 13 '22 18:11

Ali Soltani