Skip to content

Commit

Permalink
Fix x-nullable on serializers with allow_null=True (#566)
Browse files Browse the repository at this point in the history
  • Loading branch information
terencehonles committed Oct 25, 2020
1 parent 03aa143 commit 19a309a
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/drf_yasg/inspectors/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ def SwaggerType(existing_object=None, **instance_kwargs):
instance_kwargs.setdefault('title', title)
if description is not None:
instance_kwargs.setdefault('description', description)
if field.allow_null and not instance_kwargs.get('required', False) and not field.required:
if field.allow_null:
instance_kwargs['x_nullable'] = True

instance_kwargs.update(kwargs)
Expand Down
4 changes: 4 additions & 0 deletions testproj/snippets/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ class Snippet(models.Model):
class Meta:
ordering = ('created',)

@property
def nullable_secondary_language(self):
return None


class SnippetViewer(models.Model):
snippet = models.ForeignKey(Snippet, on_delete=models.CASCADE, related_name='viewers')
Expand Down
2 changes: 2 additions & 0 deletions testproj/snippets/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ class SnippetSerializer(serializers.Serializer):
rate = serializers.DecimalField(max_digits=6, decimal_places=3, default=Decimal('0.0'), coerce_to_string=False,
validators=[MinValueValidator(Decimal('0.0'))])

nullable_secondary_language = LanguageSerializer(allow_null=True)

def create(self, validated_data):
"""
Create and return a new `Snippet` instance, given the validated data.
Expand Down
20 changes: 20 additions & 0 deletions tests/reference.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,7 @@ definitions:
- code
- tags
- language
- nullableSecondaryLanguage
type: object
properties:
id:
Expand Down Expand Up @@ -1230,6 +1231,25 @@ definitions:
format: decimal
default: 0.0
minimum: 0.0
nullableSecondaryLanguage:
type: object
properties:
name:
title: Name
description: The name of the programming language
type: string
enum:
- cpp
- js
- python
default: python
readOnlyNullable:
title: Read only nullable
type: string
readOnly: true
minLength: 1
x-nullable: true
x-nullable: true
SnippetViewer:
required:
- snippet
Expand Down

0 comments on commit 19a309a

Please sign in to comment.