2017-07-03 65 views
0

我試圖把數據放入燒瓶使用和peewee的數據庫,我也遇到了以下錯誤:peewee.OperationalError: no such table: postpeewee「沒有這樣的表」錯誤

我的models.py文件如下:

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() 

我已經谷歌搜索了這一點,並且對於大多數人來說,缺乏'db.create_tables()'似乎是問題所在。很明顯,它在我的代碼中,所以我不確定錯誤來自哪裏。一些建議將不勝感激。當我嘗試使用另一個.py文件填充「文本」字段時,問題似乎就會出現。

回答

1

我適應你的代碼下面的代碼片段,它爲我的作品:

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 

你需要(在你的數據庫,即一個新行),創建一個新的Post時調用create方法。除此之外,initialize_db()似乎工作得很好。

如果你無法在數據庫上執行任何寫操作,確保你有在你正在嘗試做的是,目錄的寫權限(在這種情況下,這將是你的工作目錄)