Skip to content

Commit 245585e

Browse files
committed
Fixed DynamicFieldsModelSerializer
1 parent 335aadf commit 245585e

File tree

3 files changed

+17
-4
lines changed

3 files changed

+17
-4
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ Response:
162162

163163
It's copied from [official document](https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields).
164164

165+
When using `DynamicFieldsModelSerializer`, the settings in `Meta` such as `exclude` and `fields` are ignored. Instead, the `fields` specified in the parameter that is passed in will take precedence.
165166

166167
# Mixins
167168

rest_framework_ext/serializers.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,24 @@ def __init__(self, *args, **kwargs):
6363
# Don't pass the 'fields' arg up to the superclass
6464
fields = kwargs.pop('fields', None)
6565

66-
# Instantiate the superclass normally
67-
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
66+
if fields:
67+
if hasattr(self.Meta, 'exclude'):
68+
delattr(self.Meta, 'exclude')
69+
70+
model = getattr(self.Meta, 'model')
71+
property_fields = {name for name in dir(model) if isinstance(getattr(model, name), property)}
72+
73+
self.Meta.fields = list(
74+
set([field.name for field in model._meta._get_fields(reverse=False)]) |
75+
property_fields |
76+
set(self._declared_fields)
77+
)
6878

69-
if fields is not None:
7079
# Drop any fields that are not specified in the `fields` argument.
7180
allowed = set(fields)
7281
existing = set(self.fields)
7382
for field_name in existing - allowed:
7483
self.fields.pop(field_name)
84+
85+
# Instantiate the superclass normally
86+
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
setup(
1010
name='djangorestframework-ext',
11-
version='0.18',
11+
version='0.19',
1212
url='https://github.com/zengqiu/django-rest-framework-ext',
1313
license='MIT',
1414
author='zengqiu',

0 commit comments

Comments
 (0)