[Answered ]-Unique_together not working as expected in view

1👍

It works perfectly fine on the admin panel.

That is because it is validated by a ModelForm, you can check this before saving with .full_clean(…) [Django-doc]:

class ParentView(View):
    template_name = 'app/index.html'

    def get(self, *args, **kwargs):
        for i in range(10):
            parent = Parent(
                attribute_1=f'value-{i}',
                attribute_2=i,
                attribute_3=f'value-{i}',
            )
            parent.full_clean()
            parent.save()
        return render(self.request, self.template_name)

Most databases can enforce unique constraints, you will have to makemigrations and migrate.


Note: As the documentation on unique_together [Django-doc] says, the unique_together constraint will likely become deprecated. The documentation advises to use the UniqueConstraint [Django-doc] from Django’s constraint
framework
.

Leave a comment