@@ -232,23 +232,30 @@ def save(self, **kwargs):
232
232
for field in m2m_fields_to_commit :
233
233
getattr (self , field ).commit ()
234
234
235
- def serializable_data (self ):
236
- obj = get_serializable_data_for_fields (self )
235
+ def serializable_data (self , exclude_fields = None ):
236
+ obj = get_serializable_data_for_fields (self , exclude_fields = exclude_fields )
237
+
238
+ # normalize exclude_fields to a set
239
+ exclude = set (exclude_fields or ())
237
240
238
241
for rel in get_all_child_relations (self ):
239
242
rel_name = rel .get_accessor_name ()
240
- children = getattr (self , rel_name ).all ()
243
+ if rel_name in exclude :
244
+ continue
241
245
246
+ # define a subset of exclude_fields for this relationship
247
+ rel_exclude = {f [len (rel_name ) + 2 :] for f in exclude if f .startswith (rel_name + '__' )}
248
+
249
+ # serialize children to a list, using only the fields we need
250
+ children = getattr (self , rel_name ).all ().defer (* rel_exclude ).iterator ()
242
251
if hasattr (rel .related_model , 'serializable_data' ):
243
- obj [rel_name ] = [child .serializable_data () for child in children ]
252
+ obj [rel_name ] = [child .serializable_data (exclude_fields = rel_exclude ) for child in children ]
244
253
else :
245
- obj [rel_name ] = [get_serializable_data_for_fields (child ) for child in children ]
254
+ obj [rel_name ] = [get_serializable_data_for_fields (child , exclude_fields = rel_exclude ) for child in children ]
246
255
247
256
for field in get_all_child_m2m_relations (self ):
248
- if field .serialize :
249
- children = getattr (self , field .name ).all ()
250
- obj [field .name ] = [child .pk for child in children ]
251
-
257
+ if field .serialize and field .name not in exclude :
258
+ obj [field .name ] = list (getattr (self , field .name ).all ().values_list ('pk' , flat = True ))
252
259
return obj
253
260
254
261
def to_json (self ):
0 commit comments