Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не работает Django

Моя ошибка гласит: (1452, 'Cannot add or update a child row: a foreign key constraint fails (test_clothingapp.clothingapp_clothingitem, CONSTRAINT clothingapp_clothing_clothingType_id_f72c46ef_fk_clothinga FOREIGN KEY (clothingType_id) REFERENCES clothingapp_clothingtype (`i)')

У меня в основном есть поле модели внутри другой модели, и они связаны внешним ключом. Я пытаюсь понять, что я делаю неправильно. В основном в моем приложении я хочу, чтобы каждый предмет одежды имел свой собственный тип одежды. Вы можете добавлять и удалять предметы одежды, вы можете добавлять и удалять типы одежды.

В моей функции POST/PUT я беру данные из сериализованных данных:

 `clothingType =request.data.get("clothingType", "")`
 `clothingType = ClothingType(**clothingType)`

и преобразовать его в тип одежды

Я попытался сохранить, выполнив clothingType.save(), но затем он выдает мне более серьезную ошибку.

и затем я сохраняю все значения

clothingitem.name = name
clothingitem.location = location
clothingitem.last_worn = last_worn
clothingitem.image = image
clothingitem.user_id = user.id
clothingitem.clothingType = clothingType
clothingitem.save()

Models.py:

class ClothingItem(models.Model):
"""Model representing a clothing item"""
name = models.CharField(max_length=50)
location = models.CharField(max_length=50,blank=True)
clothingType = models.ForeignKey(ClothingType, on_delete=models.CASCADE)
last_worn = models.DateField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to="./static/images")

class Meta:
    ordering = ['-id']

def __str__(self):
    """ String for representing the the Model object."""
    return self.name
class ClothingType(models.Model):
"""Mlodel representing a clothing type."""
name = models.CharField(max_length=30)
help_text = 'Enter the clothing type (e.g. Pants, Shirts)'

def __str__(self):
    """ String for representing the the Model object."""
    return self.name

class Meta:
    ordering = ['-id']

Serializers.py:

class ClothingTypeSerializer(serializers.ModelSerializer):
class Meta:
    model = ClothingType
    fields = ['id', 'name']

class ClothingItemSerializer(serializers.ModelSerializer):
clothingType = ClothingTypeSerializer()       
class Meta:
    model = ClothingItem
    fields = ['id','name','location','last_worn','clothingType','image']

В настоящее время я пишу тесты, и именно они дают сбой: Я пытаюсь выполнить POST-запрос. Я уже задавал подобный вопрос, но разобрался с другой проблемой, но теперь передо мной стоит новая проблема. Вот тест

self.client.post('/api/clothing/',
        data=json.dumps({
            'user_id': 1,
            'name':"fav blue shirt",
            'location':"bottom drawer",
            'last_worn':"2022-08-15",
            'clothingType': {
                'id':1,
                'name':"shirt"
            },
            'image': 'blueshirt.jpeg',
        })
Вернуться на верх