Python schematics ignore rogue field name but validate its value

1.2k views Asked by At

Let's say I have the following JSON:

{
   "name": "Rob",
   "Occupation": {
        "Painter": [
             { 
                "company" : "X",
                 "years" : "1980-1997"    
             },
             {
                 "company" : "Y",
                 "years" : "1999-2000"   
             }
         ],
         "Singer": [
             {
                 "company" : "A",
                 "years" : "2001-2005"   
             }
         ]
   }
}

where the "Occupation" fields of "Painter" and "Singer" can obviously change to something else. How do I go about creating a model for this using schematics

So far I have the below:

from schematics import models, types

class Person(models.Model):
    name = types.StringType()
    occupation = types.ModelType(OccupationModel, serialized_name="Occupation")

class Occupation(models.Model):
    ## Here is where I don't know what to do!!! 
1

There are 1 answers

0
user1452759 On BEST ANSWER

So after tinkering around a lot finally found a way to do this. Funnily enough, found an example in the test case folder of the schematics module: Schematics DictType Test Case with ModelType

So here's what I did finally:

class OccupationModel(models.Model):
    company = types.StringType()
    years = types.StringType()

class Person(models.Model):
    name = types.StringType()
    occupation = types.DictType(types.ListType(types.ModelType(OccupationModel)), serialized_name="Occupation")