Python 如何将嵌套属性封送至架构?
我有一个项目的文章有不同的价格取决于他们的位置Python 如何将嵌套属性封送至架构?,python,flask,sqlalchemy,flask-restful,flask-restplus,Python,Flask,Sqlalchemy,Flask Restful,Flask Restplus,我有一个项目的文章有不同的价格取决于他们的位置 物品和物品价格型号如下: 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) titl
物品
和物品价格
型号如下:
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')
'price': fields.Integer(attribute='prices[0].price') # This one doesn't work
我不想把一篇文章的所有价格都退回给客户,只想退回他的位置价格。比如他收到一个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
})
这在使用lambda表达式时运行良好,但在文档(和)中,他们讨论了另一种方式,但我无法使其按如下方式运行:
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')
'price': fields.Integer(attribute='prices[0].price') # This one doesn't work
我错过了什么?为什么最后一个语法不起作用?我是否误解了这种语法用法?以下是文档()中的一个示例:
所以用
.0]替换[0]
。
你试过:(attribute='prices.0.price')@smundlay是的,也不起作用。@Elfayer我来晚了,但是,flask restx和flask restplus有一个未决问题,因为(attribute='prices.0.price')
没有起作用!