ORM๐Ÿน: ์žฅ๊ณ  ManyToManyField

./blog/models.py

from django.db import models


class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):
        return self.name


class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):
        return self.name


class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    number_of_comments = models.IntegerField()
    number_of_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

์œ„์˜ ๋ชจ๋ธ์„ migrateํ•˜๋ฉด DB์—๋Š” ์–ด๋–ค ํ…Œ์ด๋ธ”๋“ค์ด ์ƒ๊ธธ๊นŒ?

  • blog_blog
  • blog_author
  • blog_entry

๊ทธ๋ฆฌ๊ณ  Entry์— ManyToManyField ์„ค์ •์„ ์ƒ๊ธด!

  • blog_entry_authors
  • blog_blog
    CREATE TABLE "blog_blog" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(100) NOT NULL, "tagline" text NOT NULL)
  • blog_author
    CREATE TABLE "blog_author" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(200) NOT NULL, "email" varchar(254) NOT NULL)
  • blog_entry
    CREATE TABLE "blog_entry" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    "headline" varchar(255) NOT NULL,
    "body_text" text NOT NULL,
    "pub_date" date NOT NULL, "mod_date" date NOT NULL,
    "number_of_comments" integer NOT NULL, "number_of_pingbacks" integer NOT NULL, "rating" integer NOT NULL,
    "blog_id" integer NOT NULL REFERENCES "blog_blog" ("id") DEFERRABLE INITIALLY DEFERRED)
  • blog_entry_authors
    CREATE TABLE "blog_entry_authors" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    "entry_id" integer NOT NULL REFERENCES "blog_entry" ("id") DEFERRABLE INITIALLY DEFERRED,
    "author_id" integer NOT NULL REFERENCES "blog_author" ("id") DEFERRABLE INITIALLY DEFERRED)

ManyToManyField์€ ํ•ด๋‹น ํ•„๋“œ๋กœ ์—ฐ๊ฒฐ๋œ 2๊ฐœ์˜ ํ…Œ์ด๋ธ”์„ ์œ„ํ•œ ์ค‘๊ฐ„ ํ…Œ์ด๋ธ”์€ ๋งŒ๋“ค์–ด ์ค€๋‹น!

  • Entryํ…Œ์ด๋ธ”์—์„œ authors์— ManyToManyField๋ฅผ ํ†ตํ•ด์„œ author๋ฅผ ์—ฐ๊ฒฐํ•ด์คŒ!
  • ๊ทธ๋žฌ๋”๋‹ˆ "blog_entry_authors"๋ผ๋Š” ์ค‘๊ฐ„ ํ…Œ์ด๋ธ” ํƒ„์ƒ! ์ง !
  • ์ƒ์„ฑ๋˜๋Š” ํ…Œ์ด๋ธ”์„ ์ข€ ๋‚ด๋ง˜๋Œ€๋กœ ์ปค์Šคํ„ฐ๋งˆ์ด์ง•ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด "through"๋ฅผ ์”๋‹ˆ๋‹น!

ManyToManyField์— ๋ฐ์ดํ„ฐ ์ง‘์–ด๋„ฃ๋Š” ๋ฐฉ๋ฒ•์€ ๋ฐ”๋กœ add ๋ฉ”์†Œ๋“œ!

e = Entry.objects.get(pk=1)
b = Blog.objects.get(pk=1)
e.blog = b
e.save()

bob = Author.objects.create(name="Bob")
e.authors.add(bob)

add ๋ฉ”์†Œ๋“œ๋Š” ManyToManyField๋กœ ์ง€์ •๋œ ์†์„ฑ์—๋งŒ ๋‚˜ํƒ€๋‚˜๋Š” ๋ฉ”์†Œ๋“œ์ด๋‹น!

ManyToManyField.through_fields

๊ธฐํƒ€

Reference

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ