Django, create action over a model with m2m field linked to a model with custom private key

I've these two models:

class Vehicle(models.Model):
    """Vehicle object."""
    plate = models.CharField(max_length=255, primary_key=True)
    brand = models.CharField(max_length=255)
    model = models.CharField(max_length=255)
    owner = models.CharField(max_length=255)
    user = models.ForeignKey(

class Center(models.Model):
    """Center object."""
    user = models.ForeignKey(
    name = models.CharField(max_length=255)
    vehicles = models.ManyToManyField('Vehicle', related_name='vehicle_plate')

In my unit test, if I do:

   def test_create_center_with_existing_vehicles(self):
        """Test creating a center with existing vehicle."""

        vehicle_1 = Vehicle.objects.create(user=self.user, plate='ab123cd', brand='brand', model='model', owner='bla bla')

        payload = {
                'name': 'first center',
                'vehicles': [{'plate': 'ab123cd', 'brand': 'brand', 'model': 'model', 'owner': 'bla bla'}]

        res =, payload, format='json')

I get an error:

{'vehicles': [{'plate': [ErrorDetail(string='vehicle with this plate already exists.', code='unique')]}, {}]}

I can't intercept the flow in my CenterView, perform_create() is not interpelled neither the serializer.
Is there a validation step ? Could I override them, like the method 'get_or_create()' ?

Thanx, I'm a beginner ...

A way to intercept the validation step, by overriding.

The problem is in my model there's an unique constraint, so the validation step blocked (it tries to save a vehicle that exists).

I couldn't override the validation so I worked on , overriding create method:

def create(self, request, *args, **kwargs): serializer = self.get_serializer(

    # **start pre-validation* #
    initial_data_vehicles = serializer.initial_data.get('vehicles', [])
    if len(initial_data_vehicles) > 0:
        serializer.initial_data['vehicles'] = []
    existing_vehicles = []
    for vehicle in initial_data_vehicles:
        exists = Vehicle.objects.filter(user=self.request.user,plate=vehicle['plate']).exists()
        if exists:
    # **end* #

    # Step 1.
    center = self.perform_create(serializer)
    # Step 2.
    for vehicle in existing_vehicles:
        vehicle_obj, created = Vehicle.objects.get_or_create(user=self.request.user, **vehicle)

    headers = self.get_success_headers(
    return Response(, status=status.HTTP_201_CREATED, headers=headers)
Back to Top