Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – UniqueConstraint not created

I am trying to enforce a constraint for mysql where user is prohibited from inserting twice the same name and model. E.g This should not be allowed to be inserted twice: name:Name1 model:Model1

#Model
class Car(models.Model):
    name = models.CharField(max_length=100)
    model = models.CharField(max_length=100)

#View
class CarListCreateAPIView(generics.ListCreateAPIView):

    serializer_class = CarSerializer
    def get_queryset(self):
        trip_code = self.kwargs.get("pk")
        return Car.objects.filter(trip = trip_code) #Return cars for given trip

#Seializer
class CarSerializer(serializers.ModelSerializer):
    class Meta:
        model = Car
        fields = ('__all__')
        constraints = [
            models.UniqueConstraint(fields=['name', 'model'], name='car_name_model_constraint')
        ]

The problem is that the constraint is never created and thus not enforced. What might be the issue with the code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use unique_together in class Meta in Model like that:

class Car(models.Model):
    name = models.CharField(max_length=100)
    model = models.CharField(max_length=100)
   
    class Meta:
        unique_together = ['name','model']

More on that here: https://docs.djangoproject.com/en/4.0/ref/models/options/#unique-together

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading