我正在使用flask
构建SqlAlchemy
应用程序,我想从author
对象本身的Notification
对象中检索Notification
,而不是将所有User
解析为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))
但是,我不想解析数据库中的所有Users以便从每个通知中获取作者信息,而是想从Notification对象本身访问模板中的author User对象,如下所示:
在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
是id
的{{1}},是唯一标识符,其User
和primary key
也是唯一标识符。
我也可以some_author_username
,而filter_by(id=some_author_id)
是some_author_id
的{{1}}也是User
标识符。