-
Notifications
You must be signed in to change notification settings - Fork 2
Defining models
Rob edited this page Aug 30, 2013
·
2 revisions
Defining a model is done using a JSON Schema-like JSON document, designed to be portable across different languages. Warmongo does not currently support all the features of JSON-schema, but a subset of them that are rather useful.
To define a schema:
schema = {
# The "name" property is required, and is the name of the model
"name": "Country",
# "collectionName" is optional, if not provided then Warmongo will use a pluralized version of "name"
"collectionName": "countries",
# "databaseName" is optional, it is the name of the database that this model resides in. Defaults to
# the first database that is connected to
"databaseName": "mydb",
# "properties" is also required, which is a list of all the fields in your model
"properties": {
"name": {
"type": "string",
# if "required" is true, Warmongo will throw an exception of an object is created without
# this field
"required": true
},
"abbreviation": {
"type": "string",
# If the field was not specified, Warmongo will set it to the default given here
"default": ""
}
},
# "additionalProperties": if set to True (the default) then Warmongo will allow you to define new
# properties that aren't in the "properties" field
"additionalProperties": False
}
Once your schema is defined, you can create the Python class:
Country = warmongo.model_factory(schema)
canada = Country({"name": "Canada", "abbreviation": "ca"})
canada.save()
Since additionalProperties
was set to False
, the following will raise a ValidationError
:
canada.languages = ["en", "fr"]
These actions will also raise a validation error:
canada.name = 5 # field is a string, not a number
unnamed_country = Country() # no name provided