./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์๋ ์ด๋ค ํ
์ด๋ธ๋ค์ด ์๊ธธ๊น?
๊ทธ๋ฆฌ๊ณ Entry์ ManyToManyField ์ค์ ์ ์๊ธด!
- 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)
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๋ก ์ง์ ๋ ์์ฑ์๋ง ๋ํ๋๋ ๋ฉ์๋์ด๋น!