【发布时间】:2020-03-07 11:28:46
【问题描述】:
我正在使用SqlAlchemy 构建一个flask 应用程序,并且我想从Notification 对象本身从Notification 对象中检索author,而不是将所有Users 解析为一个template 以便捕获author 的数据。
这是我的模型:
在app/models.py
from app import db
from datetime import datetime
#...
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(250), unique=True, index=True)
password_hash = db.Column(db.Binary(72))
notifications = db.relationship('Notification', backref='recipient', lazy='dynamic')
#...
class Notification(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
pending = db.Column(db.Boolean, default=True)
author = ?
在我的路线中,我总是将 notifications 中的 current_user 解析为参数,因为我在 templates/base.html 导航栏中使用它(以及我的所有视图 {% extends "base.html %})
这是一个路线示例:
在app/routes.py
@app.route('/')
@app.route('/index')
def index():
notifications = User.query.filter_by(id=current_user.id).first().notifications.all()
else:
notifications = []
return(render_template('index.html', title=_('Home'), notifications=notifications))
但是,我不想解析数据库中的所有用户以便从每个通知中获取作者信息,而是想从 Notification 对象本身访问我的模板中的作者用户对象,如下所示:
在app/templates/index.html
{{ notification.author.username }}
这应该返回它的用户名。
我必须采取什么样的关系或技巧才能实现这一目标?
P.S:作为用户(通知recipient)可能会以某种方式利用它从author(例如nothification.author.password_hash)访问不需要的数据,这会不会有任何不安全性?如果是这样,实现我正在尝试的最佳方式是什么?
编辑
为了澄清这个问题,正如@noslenkwah 所指出的,我想明确指出author 是User,我希望我可以通过分配如下内容来创建Notification 对象:
notification = Notification(body='example', user_id=some_recipient_id, author = User.query.filter_by(username=some_author_username).first())
然后我可以db.session.add(notification),最后是db.session.commit()。
some_recipient_id 是User 的id,是唯一标识符,其primary key 和some_author_username 也是唯一标识符。
我也可以filter_by(id=some_author_id),而some_author_id 将是User 的primary key 和unique 标识符。
【问题讨论】:
-
作者是什么?是
User吗?作者是如何确定的?在创建Notification对象时是否可以轻松定义? -
嗨@noslenkwah,谢谢你的提问,我会更新这个问题。作者是用户,我希望我可以通过运行
not = Notification(body='something',user_id=some_integer,author=User.query.filter_by(id=some_integer).first())从flask shell 创建一个将作者设置为用户的通知对象,然后我将运行db.session.add(not)和db.session.commit(),或者我将创建一个route以在运行应用程序时创建一个Notification,并使用它自己的template,包含填充所有必需属性的字段。 -
你可以这样做。你的答案可以在this问题中找到
-
@noslenkwah ,非常感谢您指出这个问题。我已经设法解决了阅读解决方案的问题!
标签: python database flask sqlalchemy relationship