所以我的问题就在这段代码的最底层,它表示"对于查询中的b"。目标是,如果人们评论另一个人的帖子,那么将所有评论的用户名和内容显示到主帖。错误是peewee.OperationalError:没有这样的表:user。它打印i.content很好,但在我尝试打印b.user.username后抛出错误。
import datetime
from peewee import *
db = SqliteDatabase('practice2.db')
class User(Model):
"""creates the database attributes"""
username = CharField(unique=True)
email = CharField(unique=True)
password = CharField(max_length=100)
joined_at = DateTimeField(default=datetime.datetime.now)
class Meta:
"""creates the database"""
database = db
class Post(Model):
"""creates the database attributes"""
timestamp = DateField(default=datetime.date.today)
user = ForeignKeyField(
rel_model=User,
related_name='posts'
)
title = TextField()
content = TextField()
resources_to_remember = TextField()
time_spent = TextField()
tags = TextField()
class Meta:
"""creates the database"""
database = db
class CommentPost(Model):
timestamp = DateField(default=datetime.date.today)
user = ForeignKeyField(
rel_model=User,
related_name='user_posts'
)
related_post = ForeignKeyField(
rel_model = Post,
related_name = 'com_posts')
content = TextField()
def initialize():
"""connects to the database"""
db.connect()
db.create_tables([User, Post, CommentPost], safe=True)
def practice():
try:
w = User.create(username="George", email="george@gmail.com", password="KLJSklsjdfkald")
f_int = User.get(username="George")
r = Post.create(user= f_int.id, title="My First Post", content="So yeah this is my first post I think it is good.", resources_to_remember="wikipedia", time_spent="23 minutes", tags="hobbies")
s = Post.create(user= f_int.id, title="My Second Post", content="So yeah this is my second post I think it is good.", resources_to_remember="brittanica", time_spent="24 minutes", tags="hobbies")
v = CommentPost.create(user=w.id, related_post=r.id, content="Hey, see you tomorrow.")
except IntegrityError:
pass
else:
print("it worked")
print("")
a = Post.get(Post.title=="My First Post")
for i in a.com_posts:
print(i.content)
query = CommentPost.select(CommentPost, User).join(User).where(CommentPost.content == i.content)
for b in query:
print(b.user.username)
print("")
if __name__ == '__main__':
initialize()
practice()
答案 0 :(得分:1)
你忘了添加:
class Meta:
"""creates the database"""
database = db
内部课程:CommentPost
因此未创建。