2

場所によって価格が異なる記事を含むプロジェクトがあります。

Articleおよびモデルは次のArticlePriceとおりです。

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship

db = SQLAlchemy()

class Article(db.Model):
    __tablename__ = 'article'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255), nullable=False)
    description = db.Column(db.Text)
    prices = relationship("ArticlePrice")

class ArticlePrice(db.Model):
    __tablename__ = 'article_prices'

    id = db.Column(db.Integer, primary_key=True)
    article_id = db.Column(db.Integer, db.ForeignKey("article.id"), nullable=False)
    location_id = db.Column(db.Integer, db.ForeignKey("location.id"), nullable=False)
    price = db.Column(db.Integer, nullable=False)
    location = relationship('Location')

商品のすべての価格をクライアントに返すのではなく場所の価格だけを返します。彼は次のような JSON を受け取ります。

{
  id: '',
  title: '',
  description: '',
  price: 0
}

したがって、私のスキーマは次のようになります。

article = namespace.model('Article', {
    'id': fields.Integer(required=True),
    'title': fields.String(required=True),
    'description': fields.String(required=True),
    'price': fields.Integer(attribute=lambda x: x.prices[0].price), # This one works
})

これはラムダ式で正常に動作していますが、ドキュメント (フラスコレストフルとフラスコレストプラス) では別の方法について話していますが、次のように動作させることはできません:

'price': fields.Integer(attribute='prices[0].price') # This one doesn't work

私は何が欠けていますか?最後の構文が機能しないのはなぜですか? この構文の使い方を誤解していませんか?

4

1 に答える 1

1

ドキュメントの例を次に示します ( http://flask-restplus.readthedocs.io/en/stable/marshalling.html#renaming-attributes ):

model = {
    'name': fields.String(attribute='people_list.0.person_dictionary.name'),
    'address': fields.String,
}

したがって、次のように置き換えるだけ[0]です.0.

于 2018-07-16T08:07:55.440 に答える