python - 如何在mongoengine中过滤EmbeddedDocument并获取字段的值?

标签 python flask mongoengine

我正在研究将交易作为嵌入文档的积分模型。以下是它的存储结构。

{
    "_id" : ObjectId("546dae8cc09e5f0d9602e632"),
    "user" : ObjectId("53e7fdaac09e5f12a1230c14"),
    "transaction" : [ 
        {
            "date" : ISODate("2014-11-20T12:34:12.878Z"),
            "amount" : 100,
            "follow_num" : "d5571d91-e434-4b10-bbd8-2a6511e78011",
            "memo" : "test1",
            "trans_type" : "deposit",
            "status" : "success"
        }, 
        {
            "date" : ISODate("2014-11-20T13:03:49.851Z"),
            "amount" : 500,
            "follow_num" : "2fd57cf4-eb5d-4751-9c88-6158adda6572",
            "memo" : "test2",
            "trans_type" : "withdraw",
            "status" : "failed"
        }, 
        {
            "date" : ISODate("2014-11-20T22:54:19.892Z"),
            "amount" : 20,
            "follow_num" : "c2bd7dd2-3b17-41c2-9513-60a058a5622a",
            "memo" : "test3",
            "trans_type" : "deposit",
            "status" : "success"
        }
    ]
}

我想检索最近一次成功存款交易的金额 (即 transaction.trans_type="deposit"和 transaction.status = "success")。

@property
def last_deposit(self):
    credit_obj = Credits.objects.get(user=self,
                               transaction__match={"trans_type":"deposit","status":"success"})

最佳答案

如果我理解正确,那么您在使用嵌入文档中的字段进行查询时遇到了问题。您可以使用双下划线来查询嵌套字段。另外,您应该使用 filter() 而不是 get(),因为 het 用于仅匹配单个文档的查询(如果更多文档实际上会返回错误)找到的文档多于一份)。

  credit_obj = Credits.objects.filter(
    user=user_id,
    transaction__trans_type="deposit",
    transaction__status="success"
  ).order_by('-transaction__date').first()

此外,如果您使用 get(),您应该捕获可能的异常。

from mongoengine.errors import DoesNotExist, MultipleObjectsReturned
from bson.errors import InvalidId

try:
  credit_obj = Credits.objects.get(
    user=user_id,
  )

# verify that user_id is a valid ObjectID
except InvalidId:
  print "Not a valid ObjectId: '%s'." % str(user_id)
  # code to handle error

except DoesNotExist, e:
  print "Could not get '%s'. Error: %s" % (user_id, e)
  # code to handle error

except MultipleObjectsReturned:
  print "Multiple objects matched query."
  # code to handle error

关于python - 如何在mongoengine中过滤EmbeddedDocument并获取字段的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27057397/

相关文章:

python - 我可以在 Tkinter 应用程序上获取 Youtube 缩略图吗

python - 从heroku控制台连接到MongoHQ(heroku run python)

django-views - 如何使用带有mongoengine的django rest过滤进行列表过滤

python - 锁定多处理包不起作用

python - 帮我用 f-string 修复这个代码吗?

python - Django 模板语言 : Using a for loop with else

python - 如何使用 flask 和 sqlalchemy 进行选择查询?

python - 模板文件更改时重新加载 Flask 应用程序

python - Twisted/Cyclone/Tornado 的高阶网络框架/附加组件(网络登录/用户/管理员)?

python - Heroku 中的 bson 更新后 Flask 应用程序损坏