dev/error

django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row

Jayce_kim 2022. 3. 20. 22:37

django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`readme`.`products`, CONSTRAINT `products_author_id_4e72eb3c_fk_authors_id` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`))')

 


unit test 를 진행하던 와중에 뜬 에러

setUp 에서 product_id가 참조할 author_id 가 없다는 뜻

class ReviewTest(TestCase):
    def setUp(self):
        Category.objects.create(
            id   = 1,
            name = '베스트셀러'
        )
        Product.objects.create( 
            id            = 1,
            name          = '빨간책',
            category_id   = 1,
            publisher_id  = 1,         # 이 부분에서 발생
            translator_id = 1,         # 이 부분에서 발생
            author_id     = 1,         # 이 부분에서 발생
            description   = '책 설명',
        )
		Author.objects.create(
            id   = 1,
            name = '김작가'
        )
        Translator.objects.create(
            id   = 1,
            name = '김번역'
        )
        Publisher.objects.create(
            id   = 1,
            name = '출판사'
        )

Product 테이블 관련 쿼리문의 위치를 Publisher 아래로 위치하여 해결함