关于保存的mongoengine OperationError

时间:2013-05-23 23:08:10

标签: python django mongodb mongoengine

我正在编写一个python脚本来填充mongodb数据库,我的模型如下所示:

from mongoengine import *
from mongoengine.django.auth import User

class TrackGroup (Document):
    name = StringField(required=True)
    users = ListField(ReferenceField('User'))
    devices = ListField(ReferenceField('Device'))

class Device(Document):
    name = StringField(max_length=50, required=True)
    grp = ListField(ReferenceField(TrackGroup))

class User(User):
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)
    grp = ListField(ReferenceField(TrackGroup))

我的脚本是这样的:

#Create a group
gName = 'group name'
g = TrackGroup(name=gName)
g.users = []
g.devices = []
g.save()

#create a user
u = User.create_user(username='name', password='admin', email='mail@ex.com')
gRef = g
u.grp = [gRef, ]
u.first_name = 'first'
u.last_name = 'last'
u.save()
gRef.users.append(u)
gRef.save()

#create a device
dev = Device(name='name').save()
gRef = g
dev.grp = [gRef, ]
dev.save()
gRef.devices.append(dev)
gRef.save()     #Problem happens here

当我拨打gRef.save()时出现问题我收到以下错误:

raise OperationError(message % unicode(err))
mongoengine.errors.OperationError: Could not save document (LEFT_SUBFIELD only supports Object: users.0 not: 7)

我环顾了一会儿,here它说这意味着我正在设置一个空键的字段,如下所示:(示例来自上面的链接,而不是我的)< / p>

{
    "_id" : ObjectId("4e52b5e08ead0e3853320000"), 
    "title" : "Something", 
    "url" : "http://www.website.org", 
    "" : "", 
    "tags" : [ "international"]
}

我不知道这样一个领域可以来自哪里,但是我打开了一个mongo shell并从三个系列中查看了我的文档,我找不到这样的字段。

注意:如果我先添加设备,则在添加用户后保存组时会出现同样的错误。

1 个答案:

答案 0 :(得分:1)

我遇到了同样的错误,这个技巧对我有用:

the_obj_causing_error.reload()
/* make some change */
the_obj_causing_error.price = 5
the_obj_causing_error.save()

在更改对象之前,只需尝试reload()对象。