개발일지 <내일배움캠프> 20230411 TIL

임재훈·2023년 4월 12일
1

primary_key

장고 팀 프로젝트 진행중에 착각하고있던게 있었다
모델 필드인
foreigkey와 primary_key 를 했갈려서 작업중인
models.py 가 잘못되었었다

class Posting(models.Model):
    username = models.ForeignKey(UserModel, on_delete=models.CASCADE)
    post_id = models.IntegerField(primary_key=True) # 지금은 수정했지만 ForeignKey 로 되어있었음 
    main_content = models.TextField(null=True)
    create_at = models.DateField(auto_now_add=True)
    title = models.CharField(max_length=256)
    update_at = models.DateField(auto_now=True)
    categories = (
        ('codereview', '코드리뷰'),
        ('course', '취업진로'),
        ('coding_study', '개발공부'),
        ('study', '스터디'),
        ('free_board', '잡담'),
    )
    category = models.CharField(choices=categories, max_length=256)

ForeignKey로 설정된 필드는 다른 모델의 primary key를 참조하기 때문에, 그 자체로는 primary key가 될 수 없었다 unique=True 라고 사용해서 ForeignKey 필드를 고유한 값으로 만들 수 있었는데 이렇게 하면 post_id 를 primary key 로 사용할 수 있게 된다

0개의 댓글