1
所以我的問題是在這個代碼的最底層,它說「對於查詢中的b」。目標是,如果人們對另一個人的帖子發表了評論,則將所有評論的用戶名和內容顯示給主帖。錯誤是peewee.OperationalError:沒有這樣的表:用戶。它打印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="[email protected]", 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()
你提交了代碼並指出了有問題的一行,這很好,但你也應該解釋到底是什麼問題。這是一個錯誤嗎?如果是這樣,它究竟是什麼意思?標題不是一個好的描述。 – alfasin
好的,謝謝。我更新了描述。 – Chris