ManyToMany, ForeignKey

cj4207·2021년 5월 27일
0

Django

목록 보기
4/10
class Actor(models.Model):
    first_name    = models.CharField(max_length=45)
    last_name     = models.CharField(max_length=45)
    date_of_birth = models.DateField()

    class Meta:
        db_table = 'actors'

class Movie(models.Model):
    title        = models.CharField(max_length=45)
    release_date = models.DateField()
    running_time = models.IntegerField()
    actor        = models.ManyToManyField(Actor, db_table='movies_actors')

    class Meta:
        db_table = 'movies'

ManyToMany models.py

M2M은 중간테이블을 거치지않고 바로 해당 테이블에 참조가 가능하다.

actor = Actor.objects.get()
movie = Movie.objects.get()
movie.actor.add(actor)
movie.acror.first_name #정참조
acrot.movie_set.title  #역참조
class Actor(models.Model):
    first_name    = models.CharField(max_length=45)
    last_name     = models.CharField(max_length=45)
    date_of_birth = models.DateField()

    class Meta:
        db_table = 'actors'

class Movie(models.Model):
    title        = models.CharField(max_length=45)
    release_date = models.DateField()
    running_time = models.IntegerField()

    class Meta:
        db_table = 'movies'

class Actor_Movie(models.Model):
    actor = models.ForeignKey(Actor, on_delete=models.CASCADE)
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)

    class Meta:
        db_table = 'actors_movies'

ForeignKey models.py

ForeignKey를 이용한 M2M 모델링 중간테이블을 거쳐서 참조

actor = Actor.objects.get()
movie = Movie.objects.get()
actor_ = actor.actors_movies_set.get()
movie_ = movie.actors_movies_set.get()
actor_.movie.title
movie_.actor.first_name
movie.acror.first_name  #M2M
acrot.movie_set.title   #바로 참조 가능
------------------------
actor_.movie.title      #ForeignKey
movie_.actor.first_name #중간 테이블 통해서 해당 객체 접근
profile
안녕하세요

0개의 댓글