prawn-cake/simple-models

Use another model in ListField

grundic opened this issue · 2 comments

Here is example:

from simplemodels.fields import CharField, ListField
from simplemodels.models import Document


class Comment(Document):
    body = CharField()


class User(Document):
    name = CharField()
    comments = ListField([Comment])


data = {
    'name': 'John Smith',
    'comments': [
        {'body': 'comment #1'},
        {'body': 'seconds comment'},
        {'body': 'one more comment'},
    ]
}

if __name__ == '__main__':
    user = User(**data)
    print(user.name)
    for comment in user.comments:
        print(comment)

Right now I get an exception:

simplemodels.exceptions.ValidationError: List value {'body': 'comment #1'} has wrong type (dict), must be one of [<class '__main__.Comment'>]
List value {'body': 'seconds comment'} has wrong type (dict), must be one of [<class '__main__.Comment'>]
List value {'body': 'one more comment'} has wrong type (dict), must be one of [<class '__main__.Comment'>]

Either I'm doing something wrong or it's not implemented yet.. Would be nice to have though.

Confirm the issue, it's not implemented yet. As a workaround the following code will work

class User(Document):
    name = CharField()
    comments = SimpleField(validators=[lambda items: [Comment(**item) for item in items]])

Not that neat. I'll add this feature soon. Thanks for reporting

Added in v0.5.0