Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OpenApiSerializerFieldExtension target_class behaviour with __all__ #1224

Open
SXHRYU opened this issue Apr 17, 2024 · 1 comment
Open

OpenApiSerializerFieldExtension target_class behaviour with __all__ #1224

SXHRYU opened this issue Apr 17, 2024 · 1 comment

Comments

@SXHRYU
Copy link

SXHRYU commented Apr 17, 2024

Imagine we have a following django model:

class A(models.Model):
    a = models.CharField(max_length=64)
    b = models.CharField(null=True, default="b")
    c = models.BooleanField()

and a serializer:

class ASerializer(serializers.ModelSerializer):
    class Meta:
        model = A
        fields = "__all__"

Can I extend generated schema for field b of ASerializer using OpenApiSerializerFieldExtension without explicitly redefining the serializer field as

class BField(serializers.CharField):
    ...
class ASerializer(serializers.ModelSerializer):
    b = BField(required=False, default="b")
    ...
class BFieldFix(OpenApiSerializerExtension):
    target_class = BField
    ...

?

@tfranzel
Copy link
Owner

tfranzel commented Apr 25, 2024

I would recommend this:

  • define a custom model field class BCharField(models.CharField): pass and use it instead.
  • write your BSerializerField(serializers.CharField)
  • patch the mapping into the root class: ModelSerializer.serializer_field_mapping[BCharField] = BSerializerField
  • use your OpenApiSerializerFieldExtension BFieldFix extension as is

this will hook into the model serializer creation and use your own serializer field instead. The extension in turn will see the field being used and apply the extension. This imho the cleanest way to achieve that change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants