【发布时间】:2015-02-21 08:32:03
【问题描述】:
如果我有这样的文件:
{
"_id" : ObjectId("5497b4281a78a9120872ca32"),
"title" : "Thrifty Kitchen",
"description" : "Damn ugly",
"products" : [
ObjectId("54990eeb1a78a91a5758af75"),
ObjectId("a78a91a5758af7554990eeb1"),
ObjectId("a5758af990eeb17554a78a91")
]
}
...如果(使用 pymongo)我想将此文档传递给我的网页模板,那么哪里是插入查询的好地方呢?我知道我必须执行“$in”查询才能获得这些结果,但在 ORM 世界中,我可以在模型类上编写一个方法并公开一个“get_products”方法。在这里,由于我的视图逻辑直接与 Mongo 交互并且中间没有 ORM,处理这些分辨率的常见做法或模式是什么?
result = mongo.db.mycollection.find_one({"_id": ObjectId(collection_id)})
# wish it could be
for product in result.products:
print product.myattribute # but that will only return the ObjectId
# would you do something like this?
result.resolved_products = ... # do stuff to resolve ObjectIds
而且,我还没有在我的谷歌搜索中看到它,但是有没有人将查询嵌入到类的方法中,以便您可以向结果对象添加功能?有点像使用 ORM 但没有架构定义...
【问题讨论】:
标签: python mongodb flask pymongo