【问题标题】:Filter mongoengine query过滤 mongoengine 查询
【发布时间】:2019-07-09 19:12:56
【问题描述】:

我在过滤查询时遇到了一些问题,我不知道为什么。我所有的其他过滤器都工作得很好。

首先,我有一个 mongoDB 集合,其中的数据如下所示:

_id: generated
title: stringfield
date: Datefield
Responses: EmbeddedDocument 
    user: ReferenceField
    help: BooleanField

存储在 DB 中的当前响应(都使用同一个用户):

  • 2 次,Responses.help = False
  • 2 次,Responses.help = True

现在我想知道用户回答了多少次问题:

@queryset_manager
def responses_user(doc_cls, queryset):
    return queryset.filter(responses__user=current_user.id).count

上面的查询有效,它返回正确数量的响应(4)。现在我想给它添加一个过滤器,因为我想知道用户用 True 响应的次数。于是查询变为:

@queryset_manager
def responses_user(doc_cls, queryset):
    return queryset.filter(responses__user=current_user.id, responses__help=True).count

现在我得到一个我不明白的结果。它给了我 3。它应该是 2。我不明白关于这个的两件事:

  1. 为什么它返回 3?真是个奇数
  2. 为什么我的查询不起作用?

仅供参考,我打电话的方式是:

responses = Questions.responses_user()

所以我认为这不是问题

【问题讨论】:

  • 在开始插入文件后修改模型了吗?还可以从 mongo shell 检查文档的原始格式,也许你能找到问题
  • 删除整个问题集合并创建新问题似乎可以解决问题。我无法找到使这个查询 mallfunction 发生的变化。感谢您的提示!

标签: python mongodb mongoengine


【解决方案1】:

我可以使用raw_queries 与这样的嵌套字段一起使用:

queryset.filter(
  __raw__= {'responses.user': current_user.id, 'responses.help' = True}
).count

【讨论】:

  • 这应该与 mongoengine 的翻译方式完全相同:.filter(responses__user=current_user.id, responses__help=True) 到 pymongo,所以我很惊讶它解决了问题
  • 这使得请求更加明确。如果不混淆像 id 这样的字段,则相关查询本身应该可以工作。据我所知,“帮助”、“用户”这两个名称不是系统名称,但我通常会再保险。这是我想到的唯一想法。
猜你喜欢
  • 1970-01-01
  • 2016-08-28
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 2012-12-09
相关资源
最近更新 更多