From 5ecc532f82397fe5f7d9dcbe461426daa1a3ca31 Mon Sep 17 00:00:00 2001 From: adnanmuttaleb Date: Thu, 9 Jan 2020 15:01:41 +0200 Subject: [PATCH] Update README.md Added an example for nested objects mapping. --- README.md | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bb17c07..c01f663 100644 --- a/README.md +++ b/README.md @@ -147,9 +147,43 @@ It helps you to create objects between project layers (data layer, service layer **Note:** You can find more examples in tests package +5. **Mapping with nested objects** + +Suppose you have two classes `Person` and `MyPerson`, each one of them contains an `address` field of types `Address` and `MyAdress` respectively. And you want to map from `Person` to `MyPerson`. Initialization of the `ObjectMapper` will be: + +``` +class MyPerson: + def __init__(self): + self.address = None +class MyAdress: + def __init__(self): + self.city = None + self.street = None +class Address: + def __init__(self): + self.line = "Amman-Maka Street" +class Person: + def __init__(self): + self.address = Address() + +mapper = ObjectMapper() +mapper.create_map( + Address, + MyAdress, + { + 'city': lambda add: add.line.split('-')[0], + 'street': lambda add: add.line.split('-')[1] + } +) +mapper.create_map(Person, MyPerson) +person = mapper.map(Person(), MyPerson) +assert type(person.address) is MyAdress +assert '{}-{}'.format(person.address.city, person.address.street) == Person().address.line +``` + ## Installation * Download this project * Download from Pypi: https://pypi.python.org/pypi/object-mapper -### ENJOY IT! \ No newline at end of file +### ENJOY IT!