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

Detect ChoiceField type based on choices #260

Closed
mofr opened this issue Dec 4, 2018 · 5 comments · Fixed by #264
Closed

Detect ChoiceField type based on choices #260

mofr opened this issue Dec 4, 2018 · 5 comments · Fixed by #264

Comments

@mofr
Copy link
Contributor

mofr commented Dec 4, 2018

Background

According to DRF documentation and source code, ChoiceField class supports different values types.
ChoiceFieldInspector considers ChoiceField to be of string type in all cases (except ModelSerializer case).

Goal

Detect field type based on provided choices types.
When all choices are integers, set swagger type to "integer", otherwise use "string".

Open questions

  1. Are there any other types which can be automatically inferred?
@mofr
Copy link
Contributor Author

mofr commented Dec 4, 2018

Please, refine the idea and I'm ready to create a pull request for the improvement. Thank you!

@axnsan12
Copy link
Owner

axnsan12 commented Dec 4, 2018

Are there any other types which can be automatically inferred?

Currently the type is inferred from the type of the associated model field, if any.

You suggestion could also work, but, being based on a heuristic, should be implemented to err on the side of caution against false positives.

@axnsan12
Copy link
Owner

axnsan12 commented Dec 4, 2018

get_basic_type_info_from_hint could be reused to implement this, something like

if isinstance(serializer, serializers.ModelSerializer):
    ...
else:
    enum_value_types = {type(v) for v in enum_values}
    if len(enum_value_types) == 1:
        values_type = get_basic_type_info_from_hint(next(iter(enum_value_types)))
        if values_type:
            enum_type = values_type.get('type', enum_type)

@mofr
Copy link
Contributor Author

mofr commented Dec 4, 2018

I also want to improve the function to work with nested types, like List[str]. What is better works for you - two separate pull requests or a single one?

@axnsan12
Copy link
Owner

axnsan12 commented Dec 4, 2018

Whatever works for you 😄

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

Successfully merging a pull request may close this issue.

2 participants