Django JSONField has specific keys
My class looks like this:
class Foo(models.Model):
known_by = JSONField()
My data looks like
{ "known_by" : [
{'by':'name1', 'value':['def']},
{'by':'name2', 'value':['bar']}
]
}
Is there a way for me to ensure that it Jsonfield
has to follow the by,value[]
dict format . I know how to do this usingserialiazers
Any other cleaner ways of ensuring this (in the very definition of the model)? Thanks to
+3
source to share
3 answers
You can add a validator to the model field, for example:
class Foo(models.Model):
known_by = ArrayField(JSONField(max_length=100), size=4, validators=[a_json_array_validator])
And the validator:
def a_json_array_validator(value):
if any([not is_json_valid(entry) for entry in value]):
raise ValidationError(
_('%(value) is not a valid json'),
params={'value': value},
)
(The actual json validation is up to you) ;-) Note that the validators receive python objects, so it is actually a dict.
+2
source to share
Why not just override the save method to force the execution?
class Foo(models.Model):
known_by = JSONField()
def save(self, *args, **kwargs):
# begin validation code
# end validation code
if valid:
super(Model, self).save(*args, **kwargs)
else:
# something else, maybe http error code?
0
source to share