Skip to content

Commit

Permalink
add option to disable Null/Blank enum choice feature #185
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Nov 13, 2020
1 parent bc4a254 commit 05e4b90
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
9 changes: 5 additions & 4 deletions drf_spectacular/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,11 @@ def create_enum_component(name, schema):
components = [
create_enum_component(enum_name, schema=enum_schema)
]
if '' in prop_enum_original_list:
components.append(create_enum_component('BlankEnum', schema={'enum': ['']}))
if None in prop_enum_original_list:
components.append(create_enum_component('NullEnum', schema={'enum': [None]}))
if spectacular_settings.ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE:
if '' in prop_enum_original_list:
components.append(create_enum_component('BlankEnum', schema={'enum': ['']}))
if None in prop_enum_original_list:
components.append(create_enum_component('NullEnum', schema={'enum': [None]}))

if len(components) == 1:
prop_schema.update(components[0].ref)
Expand Down
2 changes: 2 additions & 0 deletions drf_spectacular/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@

# enum name overrides. dict with keys "YourEnum" and their choice values "field.choices"
'ENUM_NAME_OVERRIDES': {},
# Adds "blank" and "null" enum choices where appropriate. disable on client generation issues
'ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE': True,

# function that returns a list of all classes that should be excluded from doc string extraction
'GET_LIB_DOC_EXCLUDES': 'drf_spectacular.plumbing.get_lib_doc_excludes',
Expand Down
10 changes: 10 additions & 0 deletions tests/test_postprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ def test_postprocessing(no_warnings):
assert_schema(schema, 'tests/test_postprocessing.yml')


@mock.patch(
'drf_spectacular.settings.spectacular_settings.ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE', False
)
def test_no_blank_and_null_in_enum_choices(no_warnings):
schema = generate_schema('a', AViewset)
assert 'NullEnum' not in schema['components']['schemas']
assert 'BlankEnum' not in schema['components']['schemas']
assert 'oneOf' not in schema['components']['schemas']['B']['properties']['language']


@mock.patch('drf_spectacular.settings.spectacular_settings.ENUM_NAME_OVERRIDES', {
'LanguageEnum': 'tests.test_postprocessing.language_choices'
})
Expand Down

0 comments on commit 05e4b90

Please sign in to comment.