【问题标题】:Pymongo query normally, but Mongoengine query nothingPymongo查询正常,但Mongoengine什么也没查询
【发布时间】:2014-11-09 12:03:28
【问题描述】:

很奇怪:Pymongo 查询正常,但 Mongoengine 什么也不查询:

class VkWallPostListView(ListView):
    model = VkWallPost
    context_object_name = "vk_list"

    def get_template_names(self):
        return ["blog/vk_list.html"]

    def get_queryset(self):
        wallposts = VkWallPost.objects
        if 'all_posts' not in self.request.GET:
            #wallposts = wallposts.filter(text='S')
            wallposts = VkWallPost._get_collection().find({"text":'S'})
        tag = self.request.GET.get('tag', None)
        if tag:
            wallposts = wallposts.filter(tags=tag)

        return wallposts 

选项 wallposts = VkWallPost._get_collection().find({"text":'S'}) 返回对象,但相同的 Mongoengine wallposts = wallposts.filter(text='S') 不起作用 - 空结果,没有错误! 更多:我有相同的类来查询另一个集合 - Mongoengine 正常工作。

【问题讨论】:

  • 如果 VkWallPost 是您的 mongoengine 模型,那么您可以使用 VkWallPost.objects(text='S') 过滤我们的对象
  • @Rajsubit - 也许你错过了这一行 wallposts = VkWallPost.objects - 完全相同的已经完成

标签: django mongodb pymongo mongoengine


【解决方案1】:

看起来您的 VkWallPostListView 没有直接继承自 mongoengine.Document。我最近也遇到过这种情况,当查询时,与数据库模式相同的模型从基类 Document 以外的其他东西继承时没有返回任何内容。事实证明,mongoengine 在子类文档中添加了一个名为_cls 的隐藏字段,并在查询时自动检查。

例如:

如果我有一个 TextHolder 类,它是我的 Post 类的基础

class TextHolder(mongoengine.Document):
    text = mongoengine.StringField()
    meta = { 'allow_inheritance' : True,
             'abstract' : True }

class Post(TextHolder):
    user = mongoengine.ReferenceField(User)

如果我尝试通过数据库中已存在的帖子进行查询,他们将不会在其文档中定义_cls 字段。所以,查询不符合这个标准的文档的方法就是这样做。

Post.objects(user=user_to_query_by, class_check=False)

这将使我忽略_cls 字段并且不检查与当前模型的类名匹配的所有对象。

【讨论】:

  • 我遇到了同样的问题并将meta = {'allow_inheritance': False} 添加到子类(您的Post)中,之后一切正常(我不必再指定class_check=False)。
猜你喜欢
  • 2014-08-16
  • 2015-07-16
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 2013-03-07
  • 2010-12-17
  • 1970-01-01
  • 2020-10-07
相关资源
最近更新 更多