Skip to content

Django 3.16 not checking DEFERRED unique constraints #9697

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Enorio opened this issue May 9, 2025 · 0 comments
Open

Django 3.16 not checking DEFERRED unique constraints #9697

Enorio opened this issue May 9, 2025 · 0 comments

Comments

@Enorio
Copy link

Enorio commented May 9, 2025

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_a = [
    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 voice_calling, 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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant