Models

The models module contains the booby highest level abstraction: the Model.

To define a model you should subclass the Model class and add a list of fields as attributes. And then you could instantiate your Model and work with these objects.

Something like this:

class Repo(Model):
     name = StringField()
     owner = EmbeddedField(User)

booby = Repo(
    name='Booby',
    owner={
        'login': 'jaimegildesagredo',
        'name': 'Jaime Gil de Sagredo'
    })

print booby.to_json()
'{"owner": {"login": "jaimegildesagredo", "name": "Jaime Gil de Sagredo"}, "name": "Booby"}'
class models.Model(**kwargs)[source]

The Model class. All Booby models should subclass this.

By default the Model’s __init__() takes a list of keyword arguments to initialize the fields values. If any of these keys is not a field then raises errors.FieldError. Of course you can overwrite the Model’s __init__() to get a custom behavior.

You can get or set Model fields values in two different ways: through object attributes or dict-like items:

>>> booby.name is booby['name']
True
>>> booby['name'] = 'booby'
>>> booby['foo'] = 'bar'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
errors.FieldError: foo
Parameters:**kwargs – Keyword arguments with the fields values to initialize the model.
update(dict_=None, **kwargs)[source]

This method updates the model fields values with the given dict. The model can be updated passing a dict object or keyword arguments, like the Python’s builtin dict.update().

Parameters:
  • dict – A dict with the new field values.
  • **kwargs – Keyword arguments with the new field values.
validate()[source]

This method validates the entire model. That is, validates all the fields within this model.

If some field validation fails, then this method raises the same exception that the field.validate() method had raised.

to_dict()[source]

This method returns the model as a dict.

to_json(*args, **kwargs)[source]

This method returns the model as a json string. It receives the same arguments as the builtin json.dump() function.

To build a json-serializable object for this model this method uses the Model.to_dict() method.

Project Versions

Previous topic

Installation

Next topic

Fields

This Page