【问题标题】:Flask + SqlAlchemy retrieve a class object from another class attributeFlask + SqlAlchemy 从另一个类属性中检索一个类对象
【发布时间】: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 所指出的,我想明确指出authorUser,我希望我可以通过分配如下内容来创建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_idUserid,是唯一标识符,其primary keysome_author_username 也是唯一标识符。 我也可以filter_by(id=some_author_id),而some_author_id 将是Userprimary keyunique 标识符。

【问题讨论】:

  • 作者是什么?是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


【解决方案1】:

感谢@noslenkwah 指向this 问题,我能够找到一种方法来完成我想要做的事情。

方法如下:

models.py

from app import db
from sqlalchemy.orm import backref
from datetime import datetime

#...

class Notification(db.Model):
    __tablename__ = 'notification'

    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    pending = db.Column(db.Boolean, default=True)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    recipient = db.relationship(User, foreign_keys=[user_id],
                                      backref=backref('notifications', order_by=id, lazy='dynamic'))
    author = db.relationship(User, foreign_keys=[author_id])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多