gpt4 book ai didi

python - 外键有问题

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:48 24 4
gpt4 key购买 nike

所以我的问题出在这段代码的最底部,其中写着“for b in query”。目标是,如果人们评论了另一个人的帖子,则显示主帖子的所有评论的用户名和内容。错误是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="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()

最佳答案

您忘记添加:

class Meta:
"""creates the database"""
database = db

类内部:CommentPost,因此未创建它。

关于python - 外键有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45204848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com