Python 如何将SQL转换为SQLAlchemy?(与DB模型形成不同的输出模型)
我有下面的SQL请求,它给了我想要的结果,但是我无法成功地使它在SQLAlchemy中工作 数据库模型 SQL请求(工作) 我想返回位于给定位置且在此位置处于活动状态的所有文章信息。加上它的Python 如何将SQL转换为SQLAlchemy?(与DB模型形成不同的输出模型),python,sqlalchemy,Python,Sqlalchemy,我有下面的SQL请求,它给了我想要的结果,但是我无法成功地使它在SQLAlchemy中工作 数据库模型 SQL请求(工作) 我想返回位于给定位置且在此位置处于活动状态的所有文章信息。加上它的价格,并且仅此位置的价格 SELECT a.*, ap.price FROM article a INNER JOIN article_prices ap ON a.id = ap.article_id WHERE ap.location_id = 1 AND ap.active = true SQLAlc
价格
,并且仅此位置的价格
SELECT a.*, ap.price
FROM article a
INNER JOIN article_prices ap ON a.id = ap.article_id
WHERE ap.location_id = 1
AND ap.active = true
SQLAlchemy,使用烧瓶(不工作)
问题
上面的代码为我提供了正确的文章。问题是它返回给我的是关系
,这给了我一系列的价格。我想返回定位文章的价格
。我该怎么用炼金术来写呢
这是正确的方法吗?您可以通过使用显式组合选项,将
文章。prices
集合限制为所有价格的子集,如中所述:
从的主实体或最后一个联接的目标实体(在本例中为ArticlePrice
)提取其关键字参数。使用允许您限制要从ArticlePrice
加载的属性集。生成的SQL与原始SQL几乎完全相同,除了ArticlePrice
–的主键:
要将价格集合解压缩为标量,请将属性=
关键字参数传递给字段构造函数:
article = namespace.model('Article', {
'id': fields.Integer,
'title': fields.String,
'description': fields.String,
'image': fields.String,
'brand': fields.String,
'price': fields.Float(attribute=lambda a: a.prices[0].price),
'category_id': fields.Integer
})
谢谢,真是太棒了!如果你想变得真正有创意,你可以在文章
和文章价格
之间创建一个单独的“LocationAwareArticle”,如果需要的话,还可以在位置
之间创建一个单独的“LocationAwareArticle”。
@namespace.route('/location/<location_id>')
class ArticleLocatedAPI():
@namespace.marshal_list_with(article, envelope='articles')
def get(self, location_id):
return Article.query.filter(Article.prices.any(active=True, location_id=location_id)).all()
article = namespace.model('Article', {
'id': fields.Integer,
'title': fields.String,
'description': fields.String,
'image': fields.String,
'brand': fields.String,
'price': fields.Float,
'category_id': fields.Integer
})
return Article.query.\
join(Article.prices).\
filter_by(active=True, location_id=location_id).\
options(db.contains_eager(Article.prices).load_only("price")).\
all()
SELECT article_price.article_id AS article_price_article_id, article_price.location_id AS article_price_location_id, article_price.price AS article_price_price, article.id AS article_id, article.title AS article_title, article.description AS article_description, article.image AS article_image, article.brand AS article_brand, article.category_id AS article_category_id
FROM article JOIN article_price ON article.id = article_price.article_id
WHERE article_price.active = 1 AND article_price.location_id = ?
article = namespace.model('Article', {
'id': fields.Integer,
'title': fields.String,
'description': fields.String,
'image': fields.String,
'brand': fields.String,
'price': fields.Float(attribute=lambda a: a.prices[0].price),
'category_id': fields.Integer
})