-
Notifications
You must be signed in to change notification settings - Fork 272
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
Dynamic ChoiceField choices collision #1114
Comments
Got it, I saw those but thought they were different since my enums have different shapes. I'll take a look at 1113. |
well that might be another related issue. due to the way DRF handles this, the enum names is lost. We can only generate a from out of the field name, and if that looks like a supoptimal solution, we emit a warning. you might also need to use the setting |
I tried with #1113 and the issue remains |
at closer inspection I now understand what you are doing. No, that is not allowed like that You are dynamically changing the serializer class on demand. Spectacular parses each serializer (class/class name tuple) once and reuses the the generated schema, when encountered again. So you only see the result of the first occurrence. There are 2 solutions.
from drf_spectacular.drainage import set_override
def __init__(self, unit_type, *args, **kwargs):
if unit_type == "length":
set_override(self, 'component_name', "FloatWithLength")
self.fields["unit"] = serializers.ChoiceField(choices=LengthUnits.choices)
else:
set_override(self, 'component_name', "FloatWithWeight")
self.fields["unit"] = serializers.ChoiceField(choices=WeightUnits.choices)
super().__init__(*args, **kwargs)
# Custom to_representation and to_internal_value not shown this is basically what But I would also recommend to use "ENUM_NAME_OVERRIDES": {
"WeightEnum": "import.path.to.WeightUnits",
...
} to have better names for you enums since, as mentioned, DRF/Django throws away the |
Thank you, that makes sense. Option 2 works! |
Describe the bug
I have these serializers:
And these choices:
LengthUnits
andWeightUnits
have different values. However, when I generate my schema, length, height, and weight all share the same type, withWeightUnits
used as the choices. So the schema incorrectly allows "3" as input for length and height units. I expected length and height to have a type withLengthUnits
as unit choices and weight to separately haveWeightUnits
as unit choices.The text was updated successfully, but these errors were encountered: