You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+44-1Lines changed: 44 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -80,19 +80,30 @@ You can use negative rules in `only` param too.
80
80
So `item.to_dict(only=('somefield', -'somefield.id'))`
81
81
will return `somefiled` without `id`. See [Negative rules in ONLY section](#Negative-rules-in-ONLY-section)
82
82
83
+
If you want to exclude specific values from the serialized output (e.g., `None` values):
84
+
```python
85
+
result = item.to_dict(exclude_values=(None,))
86
+
```
87
+
This will exclude all fields that have `None` as their value. You can exclude multiple values:
88
+
```python
89
+
result = item.to_dict(exclude_values=(None, True, ''))
90
+
```
91
+
**Note** that `exclude_values` works with hashable values only. It filters values after serialization, so it works with nested dictionaries and models as well.
92
+
83
93
If you want to define schema for all instances of particular SQLAlchemy model,
84
94
add serialize properties to model definition:
85
95
```python
86
96
classSomeModel(db.Model, SerializerMixin):
87
97
serialize_only = ('somefield.id',)
88
98
serialize_rules = ()
99
+
exclude_values = (None,) # Exclude None values for all instances
89
100
...
90
101
somefield = db.relationship('AnotherModel')
91
102
92
103
result = item.to_dict()
93
104
```
94
105
So the `result` in this case will be `{'somefield': [{'id': some_id}]}`
95
-
***serialize_only***and ***serialize_rules*** work the same way as ***to_dict's*** arguments
106
+
***serialize_only***, ***serialize_rules***, and ***exclude_values*** work the same way as ***to_dict's*** arguments
96
107
97
108
98
109
# Advanced usage
@@ -176,6 +187,38 @@ dict(
176
187
id=1
177
188
)
178
189
)
190
+
191
+
192
+
# Exclude specific values
193
+
item.to_dict(exclude_values=(None,))
194
+
195
+
dict(
196
+
id=1,
197
+
string='Some string!',
198
+
boolean=True,
199
+
flat_id=1,
200
+
rel=[dict(
201
+
id=1,
202
+
string='Some string!',
203
+
boolean=True,
204
+
non_sqlalchemy_dict=dict(qwerty=123)
205
+
)]
206
+
)
207
+
# Note: 'null' field is excluded because its value is None
0 commit comments