我有2个表,User
和Book
。用户与书籍具有一对多的关系。剥离版本是指一本书具有标题和内容。
用户模型
class User(db.Model):
''' Model to store user information '''
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True,
... other columns
books = db.relationship('Book', backref='author')
图书模型
class Book(db.Model):
''' Model to store user books '''
__tablename__ = 'book'
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
title = db.Column(db.String(120), nullable=False)
content = db.Column(db.Text, nullable=False)
... other columns
我想使用SQLAlchemy确保用户不能拥有多本相同标题的书。
通过使用title
和content
键将JSON传递给模型来生成一本书。
如果我创建2本书标题相同,然后像这样查询特定用户(g.user
是经过身份验证的用户):
item=Book.query.filter_by(author_id=g.user)
我得到以下信息:
[{'title': '"test-title"', 'content': '"test-content"'}, {'title': '"test-title"', 'content': '"test-content"'}]
那为什么当我执行以下查询时,我的查询返回false吗?
exists = Book.query.filter_by(
author_id=g.user, title=books_data['title']).scalar() is not None
如何实现我想要的?如果需要更多上下文,请告诉我。
谢谢!