Home > front end >  Django - UniqueConstraint not created
Django - UniqueConstraint not created

Time:02-25

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?

CodePudding user response:

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

  • Related