Skip to content

Commit 6e48a70

Browse files
authored
Avoid ChoiceField duplicate enum values for allow_null, allow_blank (#1085)
* Avoid duplicate enum values for allow_null, allow_blank * imports/code style * Chop down line length * isort
1 parent c68d3b2 commit 6e48a70

2 files changed

Lines changed: 23 additions & 4 deletions

File tree

drf_spectacular/plumbing.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -410,9 +410,9 @@ def build_choice_field(field):
410410
else:
411411
type = None
412412

413-
if field.allow_blank:
413+
if field.allow_blank and '' not in choices:
414414
choices.append('')
415-
if field.allow_null:
415+
if field.allow_null and None not in choices:
416416
choices.append(None)
417417

418418
schema = {

tests/test_plumbing.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@
2020

2121
from drf_spectacular.openapi import AutoSchema
2222
from drf_spectacular.plumbing import (
23-
analyze_named_regex_pattern, build_basic_type, detype_pattern, follow_field_source,
24-
force_instance, get_list_serializer, is_field, is_serializer, resolve_type_hint,
23+
analyze_named_regex_pattern, build_basic_type, build_choice_field, detype_pattern,
24+
follow_field_source, force_instance, get_list_serializer, is_field, is_serializer,
25+
resolve_type_hint,
2526
)
2627
from drf_spectacular.validation import validate_schema
2728
from tests import generate_schema
@@ -358,3 +359,21 @@ def test_analyze_named_regex_pattern(no_warnings, pattern, output):
358359
def test_unknown_basic_type(capsys):
359360
build_basic_type(object)
360361
assert 'could not resolve type for "<class \'object\'>' in capsys.readouterr().err
362+
363+
364+
def test_choicefield_choices_enum():
365+
schema = build_choice_field(serializers.ChoiceField(['bluepill', 'redpill']))
366+
assert schema['enum'] == ['bluepill', 'redpill']
367+
assert schema['type'] == 'string'
368+
369+
schema = build_choice_field(serializers.ChoiceField(
370+
['bluepill', 'redpill'], allow_null=True, allow_blank=True
371+
))
372+
assert schema['enum'] == ['bluepill', 'redpill', '', None]
373+
assert schema['type'] == 'string'
374+
375+
schema = build_choice_field(serializers.ChoiceField(
376+
choices=['bluepill', 'redpill', '', None], allow_null=True, allow_blank=True
377+
))
378+
assert schema['enum'] == ['bluepill', 'redpill', '', None]
379+
assert 'type' not in schema

0 commit comments

Comments
 (0)