๐ManyToManyField
from django.db import models
# Create your models here.
class Actor(models.Model):
first_name = models.CharField(max_length=45)
last_name = models.CharField(max_length=45)
date_of_birth=models.DateField()
movies=models.ManyToManyField('Movie')
#๊ด๊ณ๋ช
์ ์ง์ ์ง์ด์ฃผ๊ณ ์ถ์ผ๋ฉด ('Movie',db_table="actors_movies")
#ํด๋์ค๋ช
์๋ฌธ์_set ๊ฐ ์๋ ์๋ก์ด ์ด๋ฆ์ง์ ์ํ๋ฉด ('Movie',db_table="actors_movies",related_name='movie')
class Meta:
db_table='actors'
def __str__(self):
return self.first_name + self.last_name
#__str__ ํจ์:๊ฐ์ฒด๋ฅผ ๋ฌธ์์ด๋ก ํํํ ๊ฒ์ ๋ฐํ ex.<Actor:์ด์ง์ >
class Movie(models.Model):
title = models.CharField(max_length=45)
release_date = models.DateField()
running_time=models.IntegerField()
class Meta:
db_table='movies'
def __str__(self):
return self.title
#__str__ ํจ์:๊ฐ์ฒด๋ฅผ ๋ฌธ์์ด๋ก ํํํ ๊ฒ์ ๋ฐํ ex.<Movie: ๋ธ๋ก์ปค>
๋ด๊ฐ ๋ง๋ ํ
์ด๋ธ์ actors์ movies 2๊ฐ์ง๋ง
ManyToManyField()
์ ์ฌ์ฉํ์ฌ actors_movies ๋ผ๋ ํ
์ด๋ธ์ด ์๋์ ์์ฑ๋์๋ค.
actors_movies
ํ
์ด๋ธ์ id
,actor_id
,movie_id
๋ก ๊ตฌ์ฑ๋์ด์๋ค.
>>> from movies.models import Actor,Movie
>>> Movie.objects.create(title='๋ธ๋ก์ปค',release_date='2022-06-08',running_time=129)
<Movie: ๋ธ๋ก์ปค>
>>> Movie.objects.create(title='๊ธฐ์์ถฉ',release_date='2019-05-30',running_time=132)
<Movie: ๊ธฐ์์ถฉ>
>>> Movie.objects.create(title='๋ฒ์ฃ๋์2',release_date='2022-05-18',running_time=106)
<Movie: ๋ฒ์ฃ๋์2>
>>> Movie.objects.create(title='๋ถ๋ผ๋',release_date='2017-11-02',running_time=102)
<Movie: ๋ถ๋ผ๋>
>>> Actor.objects.create(first_name='์ด',last_name='์ง์',date_of_birth='1993-05-16')
<Actor: ์ด์ง์>
>>> Actor.objects.create(first_name='๋ง',last_name='๋์',date_of_birth='1971-03-01')
<Actor: ๋ง๋์>
>>> Actor.objects.create(first_name='์ก',last_name='๊ฐํธ',date_of_birth='1967-02-25')
<Actor: ์ก๊ฐํธ>
์ฒซ๋ฒ์งธ ๋ฐฉ๋ฒ
>>> Actor.objects.get(id=1).movies.add(Movie.objects.get(id=1))
>>> Actor.objects.get(id=3).movies.add(Movie.objects.get(id=1))
>>> Actor.objects.get(id=3).movies.add(Movie.objects.get(id=2))
>>> Actor.objects.get(id=2).movies.add(Movie.objects.get(id=3))
>>> Actor.objects.get(id=2).movies.add(Movie.objects.get(id=4))
๐ actor_id=1
์ ์ฐ๊ฒฐ๋ ์ํ๋ชฉ๋ก์ movie_id=1
์ถ๊ฐ
๐ actor_id=3
์ ์ฐ๊ฒฐ๋ ์ํ๋ชฉ๋ก์ movie_id=1
์ถ๊ฐ
.
.
.
๋๋ฒ์งธ ๋ฐฉ๋ฒ
>>> a1 = Actor.objects.get(id=1)
>>> a1.save() #saveํด์ค์ผํจ! ๊ผญ!
>>> a2 = Actor.objects.get(id=2)
>>> a2.save()
>>> a3 = Actor.objects.get(id=3)
>>> a3.save()
>>> m1 = Movie.objects.get(id=1)
>>> m1.save()
>>> m2 = Movie.objects.get(id=2)
>>> m2.save()
>>> m3 = Movie.objects.get(id=3)
>>> m3.save()
>>> m4 = Movie.objects.get(id=4)
>>> m4.save()
>>> a1.movie.add(m1)
>>> a2.movie.add(m3,m4)
>>> a3.movie.add(m1,m2)
#Actorํด๋์ค์ ManyToManyField()๊ฐ ์์ผ๋ actor์ movie๋ฅผ ๋ฃ๊ธฐ