diff --git a/lib/debug.py b/lib/debug.py index 6ead992e0..9c734146f 100644 --- a/lib/debug.py +++ b/lib/debug.py @@ -6,7 +6,8 @@ from models.author import Author from models.post import Post - -p1 = Post("1", "Hello") +Post.drop_table() +Post.create_table() +p1 = Post("Big whale", "Hello", "Whales", "Grant") ipdb.set_trace() diff --git a/lib/models/__init__.py b/lib/models/__init__.py index d5b061e1e..d5c33a247 100644 --- a/lib/models/__init__.py +++ b/lib/models/__init__.py @@ -1,4 +1,4 @@ import sqlite3 -CONN = sqlite3.connect('company.db') +CONN = sqlite3.connect('blogger.db') CURSOR = CONN.cursor() diff --git a/lib/models/post.py b/lib/models/post.py index 1f633479b..9366fc292 100644 --- a/lib/models/post.py +++ b/lib/models/post.py @@ -4,7 +4,7 @@ class Post(): all = {} categories = ['sports', 'news', 'pop', 'nature'] - def __init__(self, title, content, category, author_id=None, id = None): + def __init__(self, title, content, category, author_id, id = None): self.id = id self.title = title self.content = content @@ -24,4 +24,25 @@ def title(self, new_title): if isinstance(new_title, str) and 0 < len(new_title) <= 20: self._title = new_title - + @classmethod + def create_table(cls): + """ Create a new table to persist the attributes of Post instances """ + sql = """ + CREATE TABLE IF NOT EXISTS posts ( + id INTEGER PRIMARY KEY, + title TEXT, + content TEXT, + category TEXT, + author_id INTEGER, + FOREIGN KEY (author_id) REFERENCES authors(id)) + """ + CURSOR.execute(sql) + CONN.commit() + + @classmethod + def drop_table(cls): + """ Drop the table to persist the attributes of Post instances """ + sql = "DROP TABLE IF EXISTS posts" + + CURSOR.execute(sql) + CONN.commit()