swsnu / swppfall2019

31 stars 23 forks source link

[LAB6] 수업자료, ForeignKey와 ManyToManyField와 관련하여 질문이 있습니다. #157

Open jangdonghae opened 4 years ago

jangdonghae commented 4 years ago

안녕하세요 조교님. 항상 친절히 답변 주셔서 감사합니다! 랩 수업 자료를 복습하고, model design을 하던 중 궁금한 점이 생겨서 질문 드립니다.

  1. Lab6 수업자료를 보면 p35, p36의 Terminology에서는 Foreign Key가 Key의 개념으로써 하나, 또는 다중의 Field로, 관련 table의 Primary Key라고 정의되어있는 것 같습니다. Django에서는 이 개념이 아니라, 관련 table의 object를 통째로 사용하는 것인지, key 대신 object를 사용한다면 그 이유가 무엇인지 궁금합니다.

  2. Lab6 수업자료 p40을 보면 Many to Many relationship을 나타내기 위해서 추가적인 table을 만드는 것으로 되어있는데, django에서는 단순히 models.ManyToManyField로 해결이 되는 것인지 궁금합니다. 또한 실제 구현함에 있어서 주로 models.ManyToManyField를 이용해서 Many to Many relationship을 구현하는지 궁금합니다.

kyunggeunlee commented 4 years ago
  1. Django를 사용하더라도 데이터베이스는 다른 테이블의 Primary Key를 Foreign Key로 사용합니다. Django 자체는 데이터베이스가 아니라, 백엔드 개발을 위한 프레임워크일 뿐이고, 다만 Django가 개발자에게 더 직관적인 인터페이스를 제공하기 때문에 object를 통째로 foreign key로 사용하는 것처럼 보일 뿐입니다.

  2. 네 해결됩니다. Django 코드 상으로는 단순히 ManyToManyField 라는 필드를 만드는 것처럼 보이지만, 그렇게 코드를 작성하면 실제 데이터베이스는 강의슬라이드에 나온 것처럼 동작합니다.

ktaebum commented 4 years ago

추가로 ManyToManyField 관련 doc은 https://docs.djangoproject.com/en/2.2/ref/models/fields/#id1 에서 보시면

Database Representation

Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. 
By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it. 
Since some databases don’t support table names above a certain length, these table names will be automatically truncated and a uniqueness hash will be used, 
e.g. author_books_9cdf. You can manually provide the name of the join table using the db_table option.

으로 적혀있는 것을 확인할 수 있습니다