@@ -56,19 +56,40 @@ Serializing Custom Classes
56
56
57
57
To serialize a custom class, you must convert the class to a dictionary. The following
58
58
example serializes a custom class by using the ``vars()`` method, and then inserts the
59
- serialized object into a collection:
59
+ serialized object into a collection. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous`
60
+ tab to see the corresponding code:
60
61
61
- .. code-block:: python
62
+ .. tabs::
63
+
64
+ .. tab:: Synchronous
65
+ :tabid: sync
66
+
67
+ .. code-block:: python
68
+
69
+ class Restaurant:
70
+ def __init__(self, name, cuisine):
71
+ self.name = name
72
+ self.cuisine = cuisine
73
+
74
+ restaurant = Restaurant("Example Cafe", "Coffee")
75
+ restaurant_dict = vars(restaurant)
76
+
77
+ collection.insert_one(restaurant_dict)
78
+
79
+ .. tab:: Asynchronous
80
+ :tabid: async
62
81
63
- class Restaurant:
64
- def __init__(self, name, cuisine):
65
- self.name = name
66
- self.cuisine = cuisine
82
+ .. code-block:: python
67
83
68
- restaurant = Restaurant("Example Cafe", "Coffee")
69
- restaurant_dict = vars(restaurant)
84
+ class Restaurant:
85
+ def __init__(self, name, cuisine):
86
+ self.name = name
87
+ self.cuisine = cuisine
88
+
89
+ restaurant = Restaurant("Example Cafe", "Coffee")
90
+ restaurant_dict = vars(restaurant)
70
91
71
- collection.insert_one(restaurant_dict)
92
+ await collection.insert_one(restaurant_dict)
72
93
73
94
The preceding example serializes the ``Restaurant`` object into the following dictionary:
74
95
@@ -84,15 +105,29 @@ Deserializing Custom Classes
84
105
85
106
To deserialize a custom class, you must convert the dictionary back into an instance of
86
107
the class. The following example retrieves a document from a collection, and then converts
87
- it back into a ``Restaurant`` object from the preceding example:
108
+ it back into a ``Restaurant`` object from the preceding example. Select the
109
+ :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code:
110
+
111
+ .. tabs::
112
+
113
+ .. tab:: Synchronous
114
+ :tabid: sync
115
+
116
+ .. code-block:: python
117
+
118
+ def deserialize_restaurant(doc):
119
+ return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
120
+
121
+ .. tab:: Asynchronous
122
+ :tabid: async
88
123
89
- .. code-block:: python
124
+ .. code-block:: python
90
125
91
- def deserialize_restaurant(doc):
92
- return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
126
+ def deserialize_restaurant(doc):
127
+ return Restaurant(name=doc["name"], cuisine=doc["cuisine"])
93
128
94
- restaurant_doc = collection.find_one({"name": "Example Cafe"})
95
- restaurant = deserialize_restaurant(restaurant_doc)
129
+ restaurant_doc = await collection.find_one({"name": "Example Cafe"})
130
+ restaurant = deserialize_restaurant(restaurant_doc)
96
131
97
132
To learn more about retrieving documents from a collection, see the :ref:`pymongo-retrieve`
98
133
guide.
0 commit comments