8000 3.15(.1?) regression: optional fields in serializers are suddenly required (or need explicit None passed) · Issue #9345 · encode/django-rest-framework · GitHub
[go: up one dir, main page]

Skip to content
3.15(.1?) regression: optional fields in serializers are suddenly required (or need explicit None passed) #9345
Closed as not planned
@PureTryOut

Description

@PureTryOut

I have a model and serializer that have some optional fields. Since 3.15 (maybe .1 but I haven't had a chance to use .0 due to different regressions) this field is suddenly required however, breaking our API.

Model, house_number_addition is optional:

class Address(models.Model):
    street = models.CharField(max_length=255, blank=False, null=False)
    house_number = models.IntegerField(blank=False, null=False)
    house_number_addition = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields = ["street", "house_number", "house_number_addition"],
                name="%(app_label)s_%(class)s_unique",
            )
        ]

Serializer:

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ["id", "street", "house_number", "house_number_addition",]

View:

class AddressAPIView(ListCreateAPIView):
    serializer_class = AddressSerializer
    queryset = Address.objects.all().order_by("pk")

Test:

class AddressTestCase(APITestCase):
    def test_add_address_succeeds(self):
        response: Response = self.client.post("<url>", data={"street": "Test street", "house_number": 1}, format="json")
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

It works however if I modify the test to send data={"street": "Test street", "house_number": 1, "house_number_addition": None}. However that basically breaks API as our clients weren't required to specify the field at all before.

EDIT: I edited the AddressModel from my original post to include the UniqueConstraint I use which seems to be the cause of the issue here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0