Serialization is the process of transforming data into a format that can be stored or transmitted and then reconstructing it. It’s used all the time when developing applications or storing data in databases, in memory, or converting it into files.
I recently helped two junior developers at Labcodes understand serializers, and I thought it would be good to share my approach with Opensource.com readers.
Suppose you’re creating software for an e-commerce site and you have an Order that registers the purchase of a single product, by someone, at a price, on a date:
class Order:
def __init__(self, product, customer, price, date):
self.product = product
self.customer = customer
self.price = price
self.date = date
Now, imagine you want to store and retrieve order data from a key-value database. Luckily, its interface accepts and return dictionaries, so you need to convert your object into a dictionary:
def serialize_order(order):
return {
'product': order.product,
'customer': order.customer,
'price': order.price,
'date': order.date
}
And if you want to get some data from that database, you can get the dict data and turn that into your Order object:
def deserialize_order(order_data):
return Order(
product=order_data['product'],
customer=order_data['customer'],
price=order_data['price'],
date=order_data['date'],
)
This is pretty straightforward to do with simple data, but when you need to deal with complex objects made of complex attributes, this approach doesn’t scale well. You also need to handle the validation of different types of fields, and that’s a lot of work to do manually.
That’s where frameworks’ serializers are handy. They allow you to create serializers with little boilerplates that will work for your complex cases.
#django #python