非常奇怪: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正常工作。
答案 0 :(得分: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
字段的所有对象,而不是检查与当前模型的类名匹配。