Web/Django

ForeignKey와 OneToOneField

arsenic-dev 2025. 11. 19. 17:55

1. ForeignKey (1:N 관계)

ForeignKey는 여러 개가 하나를 참조하는 Many-to-One 관계이다.

  • e.g., 여러 개의 Post가 하나의 User 참조
  • e.g., 여러 개의 Order가 하나의 Customer 참조

 

Example

from django.db import models

class User(models.Model):
    username = models.CharField(max_length=100)

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,     # 유저 삭제 시 그 유저 글도 같이 삭제
        related_name='posts'          # user.posts 로 역참조 가능
    )

 

Post : User = N : 1

  • 하나의 User는 여러 개의 Post 가질 수 있음 -> user.posts.all()
  • 하나의 Post는 반드시 하나의 author(User)만 가짐 -> post.author

 

2. OneToOneField (1:1 관계)

OneToOneField는 딱 하나와만 연결되는 1:1 관계이다.

  • e.g., User 1명당 Profile 1개
  • e.g., Student 1명당 StudentCard 1개

 

Example

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='profile'
    )
    bio = models.TextField(blank=True)
    profile_image = models.ImageField(upload_to='profiles/', blank=True)

User : Profile = 1 : 1

  • 한 유저는 딱 하나의 프로필만 가질 수 있음 -> user.profile
  • 한 프로필도 딱 한 유저에만 연결됨 -> profile.user

 

OneToOneField의 경우, 내부적으로는 Unique 제약이 있는 ForeignKey라고 볼 수 있다.

'Web > Django' 카테고리의 다른 글

Django로 웹 개발하기: todo_list  (0) 2025.10.29
Django로 웹 개발하기: photo_list  (1) 2025.10.29