ets-labs / python-domain-models

Domain models framework for Python projects
BSD 3-Clause "New" or "Revised" License
22 stars 4 forks source link

DomainModel.set_data() #21

Closed rmk135 closed 8 years ago

rmk135 commented 8 years ago

The idea is to create model.set_data() method that will populate model's fields from dictionary.

Notes: Current logic should work for DomainModel.__init__() as well.

Example:

class Photo(models.DomainModel):

    id = fields.Int()
    storage_path = fields.String()

class Profile(models.DomainModel):

    id = fields.Int()
    name = fields.String()
    main_photo = fields.Model(Photo)
    photos = fields.Collection(Photo)

profile = Profile()
profile.set_data({
    'id': 1,
    'name': 'John',
    'main_photo': {'id': 1, 'storage_path': 'some/dir/where/photos/live/1.jpg'},
    'photos': [
        {'id': 1, 'storage_path': 'some/dir/where/photos/live/1.jpg'},
        {'id': 2, 'storage_path': 'some/dir/where/photos/live/2.jpg'}
    ]
})

assert profile.id == 1
assert profile.name == 'John'

assert isinstance(profile.main_photo, Photo)
assert isinstance(profile.main_photo.id, 1)

assert isinstance(profile.photos, Photo.Collection)
assert isinstance(profile.photos[0].id, 1)
assert isinstance(profile.photos[1].id, 2)
boonya commented 8 years ago

Has been released with 0.0.5 and 0.0.6 version. 0.0.5 and 0.0.6 are equal because something went wrong during release. Sorry for that.