|
46 | 46 | from rest_framework.relations import * # NOQA
|
47 | 47 | from rest_framework.fields import * # NOQA
|
48 | 48 |
|
| 49 | + |
| 50 | +# We assume that 'validators' are intended for the child serializer, |
| 51 | +# rather than the parent serializer. |
49 | 52 | LIST_SERIALIZER_KWARGS = (
|
50 | 53 | 'read_only', 'write_only', 'required', 'default', 'initial', 'source',
|
51 | 54 | 'label', 'help_text', 'style', 'error_messages',
|
@@ -73,13 +76,25 @@ def __new__(cls, *args, **kwargs):
|
73 | 76 | # We override this method in order to automagically create
|
74 | 77 | # `ListSerializer` classes instead when `many=True` is set.
|
75 | 78 | if kwargs.pop('many', False):
|
76 |
| - list_kwargs = {'child': cls(*args, **kwargs)} |
77 |
| - for key in kwargs.keys(): |
78 |
| - if key in LIST_SERIALIZER_KWARGS: |
79 |
| - list_kwargs[key] = kwargs[key] |
80 |
| - return ListSerializer(*args, **list_kwargs) |
| 79 | + return cls.many_init(*args, **kwargs) |
81 | 80 | return super(BaseSerializer, cls).__new__(cls, *args, **kwargs)
|
82 | 81 |
|
| 82 | + @classmethod |
| 83 | + def many_init(cls, *args, **kwargs): |
| 84 | + """ |
| 85 | + This method implements the creation of a `ListSerializer` parent |
| 86 | + class when `many=True` is used. You can customize it if you need to |
| 87 | + control which keyword arguments are passed to the parent, and |
| 88 | + which are passed to the child. |
| 89 | + """ |
| 90 | + child_serializer = cls(*args, **kwargs) |
| 91 | + list_kwargs = {'child': child_serializer} |
| 92 | + list_kwargs.update(dict([ |
| 93 | + (key, value) for key, value in kwargs.items() |
| 94 | + if key in LIST_SERIALIZER_KWARGS |
| 95 | + ])) |
| 96 | + return ListSerializer(*args, **list_kwargs) |
| 97 | + |
83 | 98 | def to_internal_value(self, data):
|
84 | 99 | raise NotImplementedError('`to_internal_value()` must be implemented.')
|
85 | 100 |
|
|
0 commit comments