为什么MongoEngine中的exclude()不会排除所有字段?

时间:2017-09-14 10:31:12

标签: python mongodb mongoengine

作为MongoEngine says in documentation:

  

only(* fields)仅加载此文档字段的子集。

     

post = BlogPost.objects(...)。only('title','author.name')

现在我在我自己的用户集上运行相同的内容,如下所示:

user = User.objects(__raw__=condition).only('status').get()

但是当我打印输出(print user.to_json())时,它会得到如下结果:

{"_id": {"$oid": "59ba3c7428999b08223dc4aa"}, "cover": "", "avatar": "", "dob": {"$date": 1505347200000}, "created_at": {"$date": 1505384574064}, "updated_at": {"$date": 1505384574064}, "bio": "", "location": "", "account_type": "regular", "status": "inactive", "phone": ""}

我不认为我错过了什么。

现在我使用exclude将一些字段列入黑名单:

user = User.objects(__raw__=condition).exclude('status').exclude('username').exclude('bio').exclude('email').get()

输出是:

{"_id": {"$oid": "59ba3c7428999b08223dc4aa"}, "fullname": "Mu Fullname", "password": "$pbkdf2-sha256$16366$y9lbq/Ueo5QSohSi1FrLmQ$YOLu.KzmLiDhS6BVh4cTPg7xFpYLZ/2l478jnROj0ok", "cover": "", "avatar": "", "dob": {"$date": 1505347200000}, "created_at": {"$date": 1505377384359}, "updated_at": {"$date": 1505377384359}, "bio": "", "location": "", "verification": {"email": false, "celebrity": false, "phone": false}, "account_type": "regular", "status": "inactive", "phone": ""}

usernameemail被排除在外,但不包括statusbio

我的用户模型是:

class Verification(EmbeddedDocument):
    email = BooleanField(default=False, allow_blank=True, allow_null=True)
    celebrity = BooleanField(default=False, allow_blank=True, allow_null=True)
    phone = BooleanField(default=False, allow_blank=True, allow_null=True)


class User(Document):
    email = EmailField(required=True, max_length=200, unique=True)
    # regex '^\w+$' equals [a-zA-Z_]
    username = StringField(regex='^\w+$', required=True, max_length=15, min_length=3, unique=True)
    fullname = StringField(required=True, max_length=20)
    password = StringField(required=True)
    cover = StringField(default='')
    avatar = StringField(default='')
    dob = DateTimeField(default='')
    created_at = DateTimeField(default=datetime.datetime.utcnow())
    updated_at = DateTimeField(default=datetime.datetime.utcnow())
    bio = StringField(default='')
    location = StringField(default='')
    verification = EmbeddedDocumentField(Verification, required=True)
    account_type = StringField(required=True, default='regular', choices=('page', 'regular'))
    status = StringField(required=True, default='inactive', choices=('inactive', 'active', 'block'))
    phone = StringField(regex='^$|^[0-9()\\-\\.\\s]+$', default='')

2 个答案:

答案 0 :(得分:1)

exclude似乎在文档字段被排除的情况下返回文档字段的默认值:

Exclude in mongoEngine

答案 1 :(得分:0)

exclude()only() 只影响通过线路发送的数据。

字段将只显示其默认值,因为属性不会被剥离,并且 没有延迟加载。

其实这是github上的一个问题。见https://github.com/MongoEngine/mongoengine/issues/305