简体   繁体   English

从 SQLAlchemy class 到 Z9784E91C7B2657917226BC82ZAFDD6 中的 JSON 返回混合属性

[英]Return hybrid property from SQLAlchemy class through JSON in Flask

looking for some help on the following.寻求以下帮助。

I am using flask_sqlalchemy on Python 3+.我在 Python 3+ 上使用 flask_sqlalchemy。 I have a simple User and a Training class;我有一个简单的用户和一个培训 class; definitions below.下面的定义。 I have a hybrid property on the Training class that will return a boolean indicating whether the user is subscribed to the training or not.我在 Training class 上有一个混合属性,它将返回一个 boolean 指示用户是否订阅了培训。 This works like a charm when working with the Jinja template engine, as I can use "training.is_subscribed(current_user)".当使用 Jinja 模板引擎时,这就像一个魅力,因为我可以使用“training.is_subscribed(current_user)”。

{% if training.is_subscribed(current_user) %}
<button type="button" class="btn btn-outline-success" disabled>Subscribed</button> You can no longer join
{% else %} 

However, now I'm writing a API route as well and returning JSON.但是,现在我也在编写 API 路由并返回 JSON。 I'm using a simple Schema (marshmallow_sqlalchemy) to serialize the Training instance.我正在使用一个简单的 Schema (marshmallow_sqlalchemy) 来序列化 Training 实例。 However, when trying to add "is subscribed" I run into the error indicating that I did not pass a user.但是,当尝试添加“已订阅”时,我遇到了错误,表明我没有传递用户。 Which is true, but I'm not sure how to do that.这是真的,但我不知道该怎么做。 Can you please help?你能帮忙吗?

TypeError: is_subscribed() missing 1 required positional argument: 'user'类型错误:is_subscribed() 缺少 1 个必需的位置参数:“用户”

Thanks!谢谢! Scott斯科特

Definitions定义

training_subscribers = db.Table('training_subscribers',
    db.Column('subscriber_id', db.Integer(), db.ForeignKey('user.id')),
    db.Column('training_id', db.Integer(), db.ForeignKey('training.id')))

class User(db.Model, UserMixin):

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)

    trainings = db.relationship('Training', secondary=training_subscribers,
                        backref=db.backref('subscribers', lazy='dynamic'))  

class Training(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(250), nullable=False)

    @hybrid_property
    def is_subscribed(self, user) -> bool:
        return self.subscribers.filter(
            training_subscribers.c.subscriber_id == user.id).count() > 0

class TrainingSchema(SQLAlchemySchema):
    class Meta:
        model = Training
        fields = ("is_subscribed","title", "id")

Code to get the JSON response获取 JSON 响应的代码

@mod_trainings.route('/json/bydate/<int:year>/<int:month>/<int:day>', methods=['GET'])
@login_required
def showUpcomingTrainingsJSONByDate(year, month, day):
    trainings = trainingController.getTrainingsAtDate(year, month, day)
    training_schema = TrainingSchema(many=True)
    return jsonify(training_schema.dump(trainings))

def getTrainingsAtDate(year, month, day):
    trainings_q = db.session.query(Training).filter(extract('year', Training.starts_at)==year).filter(extract('month', Training.starts_at)==month).filter(extract('day', Training.starts_at)==day).all()
    return trainings_q

training.is_subscribed is not actually method, but property, so not callable. training.is_subscribed实际上不是方法,而是属性,因此不可调用。 It's so complicated.太复杂了。 How it works, not calling a function but taking a function out.它是如何工作的,不是调用 function 而是取出 function。 Then what you get when you refer training.is_subscribed is is_subscribed(self, user) itself.那么当你提到training.is_subscribed时你得到的是is_subscribed(self, user)本身。 Therefore:所以:

TypeError: is_subscribed() missing 1 required positional argument: 'user'类型错误:is_subscribed() 缺少 1 个必需的位置参数:“用户”

occurred.发生了。

Well, what should we do?那么,我们该怎么办? It's so easy.它是如此容易。 Filter data until response JSON.过滤数据直到响应 JSON。 Rendering with current_user means must be able to get this from flask.使用current_user进行渲染意味着必须能够从 flask 获得此信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM