Skip to content

Commit 2ac6910

Browse files
author
Andy Babic
committed
Update ClusterableModel.serializable_data() to support the exclude_fields argument and support '__' in exclude_fields to control the representation of child items
1 parent 4c04221 commit 2ac6910

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

modelcluster/models.py

+16-9
Original file line numberDiff line numberDiff line change
@@ -232,23 +232,30 @@ def save(self, **kwargs):
232232
for field in m2m_fields_to_commit:
233233
getattr(self, field).commit()
234234

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 ())
237240

238241
for rel in get_all_child_relations(self):
239242
rel_name = rel.get_accessor_name()
240-
children = getattr(self, rel_name).all()
243+
if rel_name in exclude:
244+
continue
241245

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()
242251
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]
244253
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]
246255

247256
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))
252259
return obj
253260

254261
def to_json(self):

0 commit comments

Comments
 (0)