class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default="default.jpg")
password = db.Column(db.String(60), nullable=False)
osts = db.relationship("Post", backref="author", lazy=True)
def __repr__(self):
return "User({}, {}, {}, {})".format(
self.id, self.username, self.email, self.image_file
)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
def __repr__(self):
return "Post({}, {})".format(self.title, self.date_posted)
在Python shell中创建了一个示例User
:
>>> user1=User(username="A", email="A", password="A")
>>> db.session.add(user1)
>>> db.session.commit()
>>> User.query.all()
[User(1, A, A, default.jpg)]
创建了一个示例Post
,但将user_id显式设置为2,对此User
不存在。在这一步,我没有看到任何错误,并且帖子已成功添加到数据库中。
>>> post=Post(title="A", content="B", user_id=2)
>>> db.session.add(post)
>>> db.session.commit()
>>> post=Post.query.first()
>>> post.user_id
2