Many to Many Relationship

M:N

  • M has many N

  • N has many M

Naming convention

  • 1:N

    • Definition: Model singular (.user)

    • Reverse reference: model_set (.article_set)

  • M:N

    • Definition and reverse reference: Model plural (.like_users, like_articles)

M:N Relationship Access

image-20200428192056085

1. Simple Intuitive Modeling

Transfer the above diagram to models.py

  • Create patients/doctors

  • Create reservations

  • Doctor #1's reservation list

  • Patient #1's reservation list

  • Print doctor #1's patients

2. Using Intermediate Model

To directly access doctors - patients / patients - doctors, use ManyToManyField.

Declare intermediate model through through option.

image-20200428192226753

  • No need to create migration files or migrate.

    • There are no changes to the database, only differences in ORM manipulation.

  • Get doctor, patient objects

  • Patient #1's doctor list

    Patient with ManyToManyField defined uses direct reference

  • Doctor #1's patient list

    Doctor is not direct reference but reverse reference of Patient model.

    So, reference according to basic naming convention

  • related_name : reverse reference option

    Default value is {model name}_set

    image-20200428192427702
    • There are situations where reverse reference setting must be set

      • When makemigrations in django, it directly raises an error

      • ex) Author(User)-Article(Article), LikedUser(User)-Article(Article)

        • If you define both Article classes without related_name, reverse reference issues occur

3. Setting without Intermediate Model

Generally, when no additional fields are needed and only id values exist, declare as follows.

  • In this case, a table named appname_patient_doctors is created.

  • To Create/Delete in this table (to create or delete reservations), use the following methods:

Conclusion

  • When intermediate model is not needed

    • Declare ManyToManyField in specific Class (automatic intermediate table declaration)

  • When intermediate model is needed (when additional information is needed)

    • Define intermediate model first

    • Manipulate through through option in ManyToManyField in specific Class

+

  • In ManyToMany, always declare related_name in plural form!!

Getting desired values by id

Delete

Inconvenient version.

Like Feature

  • URL - variable routing

  • View - Cancel if liked, like if not liked (Toggle)

Follow Feature

  • URL - variable routing

    • accounts/1/follow

  • View

    • add if followed

    • remove if not followed

  • Template(response)

    • User detail redirect

Last updated