IntegrityError at /rooms/ UNIQUE constraint failed: office_room.id Django Rest Framework

Появилась проблема, мешающая продвигаться в обучении DRF дальше. В файле models.py есть модели, которые связаны один-ко-многим, один офис - несколько кабинетов (комнат). Создал для этих моделей свои сериализаторы, но только один из них работает правильно, а именно OfficeSerializer. Ошибка появляется тогда, когда пытаюсь POST-методом создать новый экземпляр Room. Выскакивает ошибка, но даже с этой ошибкой экземпляр модели СОЗДАЕТСЯ! Все поля заполнены верно, только ошибка совсем не в тему.

Вот описание этой ошибки:

Traceback (most recent call last):
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\mixins.py", line 19, in create
    self.perform_create(serializer)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
    serializer.save()
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\serializers.py", line 205, in save
    self.instance = self.create(validated_data)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\rest_framework\serializers.py", line 939, in create
    instance = ModelClass._default_manager.create(**validated_data)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\query.py", line 447, in create
    obj.save(force_insert=True, using=self.db)
  File "C:\Users\amate\repeat python and backend\office\task_office\office\models.py", line 41, in save
    super().save(*args, **kwargs)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\base.py", line 754, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\base.py", line 792, in save_base
    force_update, using, update_fields,
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\base.py", line 895, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
    using=using, raw=raw,
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\query.py", line 1254, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\amate\repeat python and backend\office\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: office_room.id

models.py

class Office(models.Model):
    address = models.CharField("Адрес офиса", max_length=150, null=True, blank=True)

    def __str__(self):
        return "Офис, находящийся по адресу {}".format(self.address)

    class Meta:
        verbose_name = 'Офис'
        verbose_name_plural = 'Офисы'
        ordering = ['address']



class Room(models.Model):
    number = models.CharField("Номер кабинета", max_length=5)
    count_of_places = models.IntegerField("Кол-во мест", validators=[MinValueValidator(0), MaxValueValidator(50)])
    count_of_occupied_places = models.IntegerField("Кол-во занятых мест",
                                                   validators=[MinValueValidator(0),
                                                               MaxValueValidator(count_of_places)],
                                                   editable=False, null=True, blank=True)
    count_of_free_places = models.IntegerField("Кол-во свободных мест", editable=False, null=True, blank=True)
    office = models.ForeignKey(Office, on_delete=models.CASCADE, related_name='room', null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.id:
            if self.count_of_free_places == None and self.count_of_occupied_places == None:
                self.count_of_free_places, self.count_of_occupied_places = self.count_of_places, 0
                super().save(*args, **kwargs)
                if self.office:
                    for _ in range(self.count_of_places):
                        curr_room = Room.objects.get(number = self.number, office = self.office)
                        place = Place(room = curr_room)
                        place.save()

        super().save(*args, **kwargs)

    def reset_places(self, *args, **kwargs):
        self.count_of_free_places, self.count_of_occupied_places = self.count_of_places, 0
        super().save(*args, **kwargs)

    def __str__(self):
        return "Кабинет №{}, находящийся в офисе по адресу {}".format(self.number, self.office.address)

    class Meta:
        verbose_name = "Кабинет"
        verbose_name_plural = "Кабинеты"
        ordering = ['number']

serializers.py

class OfficeSerializer(serializers.HyperlinkedModelSerializer):


    class Meta:
        model = Office
        fields = ['id', 'address']


class RoomSerializer(serializers.ModelSerializer):
    office = serializers.PrimaryKeyRelatedField(queryset=Office.objects.all())
    office_name = serializers.StringRelatedField(source='office')
    class Meta:
        model = Room
        fields = ['id', 'number', 'count_of_places', 'count_of_occupied_places', 'count_of_free_places', 'office',
                  'office_name']

Прошу помощи, уважаемые программисты.


Ответы (0 шт):