1

I am trying to put data into a database using flask and peewee, and I have come across the following error: peewee.OperationalError: no such table: post

My models.py file is below:

from peewee import *
import datetime

db = SqliteDatabase('posts.db') #create database to interact with

#create a class for blogposts
class Post(Model):
    id = PrimaryKeyField()
    date = DateTimeField(default = datetime.datetime.now)
    title = CharField()
    text = TextField()

    class Meta:
        database = db

def initialize_db():
    db.connect()
    db.create_tables([Post], safe = True)
    db.close()

I have Googled this, and for most people the lack of 'db.create_tables()' seems to be the problem. Obviously, it's in my code, so I am really not sure where the error is coming from. Some advice would be much appreciated. The problem seems to arise specifically when I try to populate the 'text' field using another .py file.

4

1 回答 1

1

I adapted your code into the following snippet and it works for me:

from peewee import *
import datetime

db = SqliteDatabase('posts.db') #create database to interact with

#create a class for blogposts
class Post(Model):
    id = PrimaryKeyField()
    date = DateTimeField(default = datetime.datetime.now)
    title = CharField()
    text = TextField()

    class Meta:
        database = db

def initialize_db():
    db.connect()
    db.create_tables([Post], safe = True)
    db.close()

initialize_db() #if db tables are not created, create them
post = Post.create(id=4, title="Some title", text="some text1") #add a new row
post.save() #persist it to db, not necessarily needed

You'll need to call the create method when creating a new Post (i.e. a new row in your database). Other than that, initialize_db() seems to work just fine.

If you are unable to perform any writes on the database, make sure you have write access in the directory where you are trying to do that (in this case, it would be your working directory)

于 2017-07-04T02:17:04.513 回答