开发者

added new boolean field to an existing django Mongoengine model, but after can not filter for this field

First my django model was like this:

class List(Document):
    owner = ReferenceField('User')
    name = StringField()
    users = ListField(ReferenceField('User'))
    created_at = DateTimeField(default=datetime.datetime.now)

After I added a new filed is_cancelled and now it is like that:

class List(Document):
    owner = ReferenceField('User')
    name = StringField()
    users = ListField(ReferenceField('User'))
    created_at = DateTimeField(default=datetime.datetime.now)
    is_cancelled = BooleanField(default = False)

I use mongoengine for django mongodb ORM. But now when i want to make a filter query:

List.objects.filter(is_cancelled=False)
returns []

I make all is_cancelled fields to False with django object:

for x in List.objects.all():
    x.is_cancelled = False
    x.save()

But I'm still getting an empty list for the query above. I'm looking a django objects' is_cancelled filed and I see is_cancelled = False

l = List.objects.all()[0]
l.is_cancelled

False

But when I look from mongodb shell. There is no filed as is_cancelled.

db.list.find()
{ "_cls" : "List", "_id" : ObjectId("4e8451598ebfa80228000000"), "_types" : [ "List" ],     
"created_at" : ISODate("2011-09-29T16:24:28.781Z"), "name" : "开发者_JS百科listname", "users" : [          
{
            "$ref" : "user",
            "$id" : ObjectId("4e79caf78ebfa80c00000001")
    },      {
            "$ref" : "user",
            "$id" : ObjectId("4e79e4df8ebfa80b64000001")
    },      {
            "$ref" : "user",
            "$id" : ObjectId("4e7aeb898ebfa80b64000001")
    },      {
            "$ref" : "user",
            "$id" : ObjectId("4e79ce028ebfa80c00000004")
    } ] }    

How can I fix this query


Voila!

This is my answer:

https://github.com/hmarr/mongoengine/issues/282

There is a bug at the mongengine BooleanField with a value of False.

But they have fixed it with this patch:

https://github.com/hmarr/mongoengine/pull/283


It is because mongoDB is a schema-less database. Although you have defined the field is_canceled in your model, that does not mean all existing documents are going to be updated with this new field. Within a collection, each document is not required to follow the same structure.

If you want the is_canceled field in each of your existing documents you will need to write an update script to iterate through each document in your collection and add that field. Otherwise, only new documents you create with this new model will contain the field is_canceled.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜