2012-08-08 176 views

回答

11

嗨,你可以使用$exists$size

import unittest 
from mongoengine import * 

class Test(unittest.TestCase): 

    def setUp(self): 
     conn = connect(db='mongoenginetest') 

    def test_list_exists_or_has_size(self): 

     class Post(Document): 
      title = StringField(required=True) 
      tags = ListField(StringField()) 

     Post.drop_collection() 

     Post(title="Hello Stackoverflow").save() 
     Post(title="Hello twitter", tags=[]).save() 
     Post(title="Hello world", tags=['post', 'blog']).save() 

     self.assertEqual(2, Post.objects(
           Q(tags__exists=False) | 
           Q(tags__size=0)).count()) 
+0

聽起來不錯!但在最終查詢中它的「存在」而不是「存在」,不是嗎?我不允許以少於6個字符的方式進行更改... – Ron 2012-08-14 07:28:27

-1

不知道完全肯定,如果這是你的意思沒有設置 ListField這樣的:

from mongoengine import * 

connect('tumblelog') 


class Post(Document): 
    title = StringField(required=True) 
    tags = ListField(StringField()) 


post1 = Post(title='Fun with MongoEngine', tags=['mongodb', 'mongoengine']) 
post1.save() 

for post in Post.objects: 
    print post.title 
    if not post.tags: 
     print '-post has no tags' 
    else: 
     print post.tags 

這將輸出:

Fun with MongoEngine 
[u'mongodb', u'mongoengine'] 
Fun with MongoEngine no tags 
-post has no tags 
相關問題