如何检查ListField()
Mongo 类的属性是否未设置或为空?
谢谢!
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())
如果您正在寻找相反的问题(检查列表是否至少包含一个暗示它也存在的元素),那么您可以使用查询字典进行更改:
query = {}
query['tags__exists'] = True
query['tags__not__size'] = 0
for post in Post.objects(**query):
print(post)
根据 MongoEngine文档,该not
运算符可用于否定标准检查,只要它位于查询运算符之前。
不完全确定这是否是空或未设置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