μ₯κ³ Many to Many κ΄κ³ν μ΄λΈμ λν΄μ μμ보μ.
μ₯κ³ μμλ Mant To many μ΅μ μ μ§μ ν μ μλλ° λ¨μν κ΄κ³ ν μ΄λΈμ λλ κ²κ³Ό Many To Manyμ΅μ μ μ§μ νμ λ μ°¨μ΄μ λν΄μ μμλ³΄κ² μ΅λλ€.
μμ λ°μ΄ν°λ μλμ κ°μ΅λλ€.
μνμ 보λ₯Ό κ°κ³ μλ μν ν
μ΄λΈκ³Ό λ°°μ° μ 보λ₯Ό λ΄κ³ μλ λ°°μ°ν
μ΄λΈ κ·Έλ¦¬κ³ μ΄ λμ μ΄μ΄μ£Όλμ€κ³ν
μ΄λΈ μ
λλ€.
class Actor(models.Model):
name = models.CharField(max_length=45)
class Movie(models.Model):
title = models.CharField(max_length=256)
class ActorMovie(models.Model):
actor = models.ForeignKey(Actor, on_delete=models.CASCADE)
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
κ°λ μ±μ μν΄μ 컬λΌμ μλ μ΅λν μ€μμ΅λλ€.
λ°μ΄ν°λ₯Ό λ£μ΄λ³΄κ² μ΅λλ€.
m1 = Movie.objects.create(title="ν
λ·")
m2 = Movie.objects.create(title="λΈλ μ΄λλ¬λ2049")
a1 = Actor.objects.create(name="μ‘΄ λ°μ΄λΉλ μμ±ν΄")
a2 = Actor.objects.create(name="λΌμ΄μΈ κ³ μ¬λ§")
ActorMovie.objects.create(actor=a1, movie=m1)
ActorMovie.objects.create(actor=a2, movie=m2)
a1.actormovie_set.all()
for actormovie in a1.actormovie_set.all():
print(actormovie.movie.title)
μν, λ°°μ° κ΄κ³ ν
μ΄λΈμ μμ°Έμ‘°ν΄μ κ°μ²΄λ₯Ό μμ±ν΄μ μμλ₯Ό νλ λΉΌμ .movie.title
λ‘ μ κ·Όν΄μΌ ν©λλ€. μ’ λ²κ±°λ‘λ€λ λλμ΄ λλλ€.
class Actor(models.Model):
name = models.CharField(max_length=45)
class Movie(models.Model):
title = models.CharField(max_length=256)
actor = models.ManyToManyField(Actor,
through='ActorMovie',
related_name='movies')
class ActorMovie(models.Model):
actor = models.ForeignKey(Actor, on_delete=models.CASCADE)
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
μ΄μ μν λ€μ μ‘΄ λ°μ΄λΉλ μμ±ν΄λ°°μ°μ μνλ₯Ό μ‘°νν΄λ³΄κ² μ΅λλ€.
a1.movies.all()
for movie in a1.movies.all():
print(movie.title)
>>> "ν
λ·"
κ΄κ³ ν
μ΄λΈμ μμ±ν κ²½μ°λ³΄λ€ λ©μλ νκ°λ₯Ό λ μΈ μ μμ΅λλ€. .movie.title
-> .title
μ’ λ μ§κ΄μ μ΄κ² κ΄κ³ν ν μ΄λΈμ μ‘°νν μ μμ΅λλ€.
class Actor(models.Model):
name = models.CharField(max_length=45)
class Movie(models.Model):
title = models.CharField(max_length=256)
actor = models.ManyToManyField(Actor,
related_name='movies')
μ΄λ κ² νλ©΄ μκΉμ κ°μ΄ λ°μ΄ν°λ₯Ό μ‘°νν μ μμ΅λλ€.
a1 = Actor.objects.create(name="μ‘΄ λ°μ΄λΉλ μμ±ν΄")
a1.movies.all()
for movie in a1.movies.all():
print(movie.title)
>>> "ν
λ·"
μ€κ³ ν μ΄λΈμ κ΄κ³νλ ν μ΄λΈ foreignkeyμΈμ λ€λ₯Ένλͺ©μ μΆκ°νκ³ μ ν λ νμν©λλ€.
μ€κ³ν μ΄λΈμ μ λ§λ€κ³ Many to Manyμ΅μ μ μ§μ νλ©΄ λ°μ΄ν°λ² μ΄μ€μ μλμΌλ‘ κ΄κ³ν μ΄λΈμ΄ μμ±λλλ° μ΄ ν μ΄λΈμ 컬λΌμ μΆκ°νκ³ μ νλ©΄ μ§μ μ₯κ³ μμ λ§λ€μ΄μΌ μΆκ°νκ³ μ νλ 컬λΌμ΄ λ°μλ©λλ€.