tfranzel/drf-spectacular

https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields

Opened this issue · 3 comments

Describe the bug
With DynamicFieldsModelSerializer from django rest framework swagger dosen't produce the full schema of object
https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields

To Reproduce
take two models with some different fields and their serializers

class ItemCategorySerializer(DynamicFieldsModelSerializer ):
class Meta:
model = ItemCategory
fields = "all"

class ItemSerializer(DynamicFieldsModelSerializer):
class Meta:
model = Item
fields = "all"

category_obj = ItemCategorySerializer(source='category', many=False, read_only=True, required=False, allow_null=True, partial=True, fields=['id', 'name', ])

I want show only fews details for ItemCategory when is inside Item so i added DynamicFieldsModelSerializer and on category_obj fields=['id', 'name', ]

when i generate full schema model of ItemCategory lose all fields except id and name, instead if i remove fields=['id', 'name', ]
the autogenerated schema will have all fields,

that is a problem because when i make my view with ItemCategory i want all fields, seems autogenerated
ItemCategorySerializer( fields=['id', 'name', ])
replace ItemCategorySerializer() called before

Expected behavior
i Expect to have all fields in my ItemCategory schema w/o create a new serializer

i found a solution, i don't like it but works
but the real problem is we can't controll order of Serializers so only the first one is generated if is already presen't wont replace the old one or extend... so i solvedin that way

@extend_schema(
request=None,
responses={
200: ItemCategorySerializer,
201: ItemSerializer,
202: CardSerializer,
203: TagSerializer,
},
)
@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def preloadSerilizers(request):
pass

and than registered that in urls patterns

i tried to add in preprocessor or postprosessor hooks but w/o any real good solution

Hi, this was discussed before in #375

please see this: #375 (comment) and #375 (comment) for a solution.

You basically need an OpenApiSerializerExtension and you also need to give each variation an individual ref_name.

fyi: for placing the extension: https://drf-spectacular.readthedocs.io/en/latest/customization.html#step-5-extensions