user1452759
user1452759

Reputation: 9450

Python schematics ignore rogue field name but validate its value

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!!! 

Upvotes: 1

Views: 1351

Answers (1)

user1452759
user1452759

Reputation: 9450

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")

Upvotes: 1

Related Questions