Skip to content

Django 3.16 not checking DEFERRED unique constraints #9697

Open
@Enorio

Description

@Enorio

I was using the rest-framework version 3.14 and have the following code:

class A(models.Model):
    ....
    class Meta:
        constraints = [
            UniqueConstraint(
                name="unique_one",
                fields=['field_a', 'field_b'],
                deferrable=Deferrable.IMMEDIATE
            ),
            UniqueConstraint(
                name='unique_two',
                fields=['field_a', 'sort_index'],
                deferrable=Deferrable.DEFERRED
            )
        ]

class ASerializer(serializers.ModelSerializer):
    class Meta:
        model = A
        fields = '__all__'
        validators = [
            UniqueTogetherValidator(
                queryset=A.objects.all(),
                fields=['field_a', 'field_b']
            )
        ]


class B(models.Model):
    ...
    class Meta:
        constraints = [
            UniqueConstraint(
                name='unique_one',
                fields=['field_a', 'sort_index'],
                deferrable=Deferrable.DEFERRED,
            )
        ]

class BSerializer(serializers.ModelSerializer):
    class Meta:
        model = B
        fields = '__all__'

My code basically has a sort_index field, that is the position of a certain A or B.
For example, if I have a list of Bs, adding a new one updates all the sort_index, following some rules:

list_of_b = [
    B(name="A", field_a=1, sort_index=1),
    B(name="B", field_a=1, sort_index=2)
]
b_serializer = BSerializer(data={"name":"C", "sort_index":1})
b_serializer.save()

# final list of Bs
list_of_b = [
    B(name="C", field_a=1, sort_index=1),
    B(name="A", field_a=1, sort_index=2),
    B(name="B", field_a=1, sort_index=3)
]

Now, with version 3.16, this raises the error {'non_field_errors': [ErrorDetail(string='The fields field_a, sort_index must make a unique set.', code='unique')]}
This error does not occur in the ASerializer, I'm guessing because I override the constraints with the validators?

Should I add validators = [] to override it, or is some configuration that uses the Deferred?

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