Django Model: One-to-Many, Many-to-Many Relationships

이다연·2021년 3월 8일
0

Django

목록 보기
9/33

There are three ways in which a table can be related to another table:

  • One-to-one: A record in one table is related to one record in another table.
  • One-to-many: A record in one table is related to many records in another table.
  • Many-to-many: Multiple records in one table are related to multiple records in another table.

Handling a one-to-one relationship or a one-or-many relationship can be done by adding the primary key of one table into the other table as a foreign key.

One-to-Many

ForeignKey is used to specify a one-to-many relationship to another database model (e.g. a car has one manufacturer, but a manufacturer can make many cars). The "one" side of the relationship is the model that contains the "key" (models containing a "foreign key" referring to that "key", are on the "many" side of such a relationship).

Many-to-Many Relationships

We use a concept called a joining table or a bridging table.
So, we have a new table called class_enrollment. It stores two columns: one for each of the primary keys from the other table.

Our table would look like this:

This stores separate records for each combination of student and class. Our student and class tables remain the same:

ManyToManyField is used to specify a many-to-many relationship (e.g. a book can have several genres, and each genre can contain several books). In our library app we will use these very similarly to ForeignKeys, but they can be used in more complicated ways to describe the relationships between groups. These have the parameter on_delete to define what happens when the associated record is deleted (e.g. a value of models.SET_NULL would set the value to NULL).

https://dzone.com/articles/how-to-handle-a-many-to-many-relationship-in-datab

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Models


profile
Dayeon Lee | Django & Python Web Developer

1개의 댓글

comment-user-thumbnail
2022년 10월 17일

Nowadays, infidelity has caused many relationships to end. I was able to get information on how to determine whether or not someone is cheating on you. Everything is on this website signs someone is hiding something on their phone . For instance, this website helped me learn a lot about treason. The website is highly useful, as are the spy software applications. I suggest you test this material out because it will be useful to you in the future.

답글 달기