django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails
(`fithubdb`.`#sql-3f9a_e2`, CONSTRAINT `community_article_user_id_2ae5b75d_fk_users_user_id`
FOREIGN KEY (`user_id`) REFERENCES `users_user` (`id`))')
User 모델에서 id를 CharField로 설정해서 외래키 참조가 불가능하다. 그냥 username으로 이름을 바꿔야 할듯
mysql> desc community_article;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| article_id | int | NO | PRI | NULL | auto_increment |
| content | longtext | YES | | NULL | |
| image | varchar(100) | YES | | NULL | |
| created_at | datetime(6) | NO | | NULL | |
| user_id | int | NO | MUL | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
mysql> desc users_user;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| password | varchar(128) | NO | | NULL | |
| last_login | datetime(6) | YES | | NULL | |
| id | int | NO | PRI | NULL | auto_increment |
| email | varchar(50) | NO | UNI | NULL | |
| username | varchar(30) | NO | | NULL | |
| is_expert | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| is_admin | tinyint(1) | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
8 rows in set (0.01 sec)
Article에서 User 참조 성공
mysql> select * from community_article;
+------------+------------------------------+-------+----------------------------+---------+
| article_id | content | image | created_at | user_id |
+------------+------------------------------+-------+----------------------------+---------+
| 5 | This is content1 of article1 | | 2024-08-15 09:53:01.849487 | 2 |
| 6 | This is content of article2 | | 2024-08-15 09:55:35.261683 | 2 |
+------------+------------------------------+-------+----------------------------+---------+
2 rows in set (0.00 sec)
ArticleListSerializer
[
{
"article_id": 5,
"content": "This is content1 of article1",
"image": null,
"created_at": "2024-08-15T18:53:01.849487+09:00",
**"user": "testuser2"**
},
{
"article_id": 6,
"content": "This is content of article2",
"image": null,
"created_at": "2024-08-15T18:55:35.261683+09:00",
**"user": "testuser2"**
},
{
"article_id": 8,
"content": "This is content of article3",
"image": null,
"created_at": "2024-08-15T19:24:34.219196+09:00",
**"user": "testuser3"**
}
]
게시글 수정
수정