Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
Django JSONField to have particular keys

My class looks like this:

class Foo(models.Model):
  known_by = JSONField()

My data looks like this

{ "known_by" : [
                {'by':'name1', 'value':['def']},
                {'by':'name2', 'value':['bar']}
               ]
}

Is there any way for me to enforce that the Jsonfield needs to follow the format of by,value[] dict. I know how to do this using serialiazers

Any other cleaner way to enforce this(in the model definition itself)? Thanks

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can add a validator to the model field, like this:

 class Foo(models.Model):
     known_by = ArrayField(JSONField(max_length=100), size=4, validators=[a_json_array_validator])

And the validator is:

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 validators receive python objects so its actually a dict.

about 4 years ago · Santiago Trujillo Report

0

You could implement it this way:

from django.db import models

class Bar(models.Model):
    by = models.CharField()
    value = models.ArrayField()


class Foo(models.Model):
    known_by = models.ForeignKey(Bar, on_delete=models.CASCADE)
about 4 years ago · Santiago Trujillo Report

0

Why not just override the save method to do the enforcement?

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?
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!