[英]How to atomically remove a key from a dictionary in Mongoengine/Pymongo?
So it's mainly a Mongoengine question but looking at the error the issue seems to be in the underlying pymongo layer so I figure I should mention both. 因此,这主要是一个Mongoengine问题,但从错误的角度看,问题似乎在底层的pymongo层中,因此我认为我应该同时提及这两个问题。 Basically i have a model like this Edit: Updated to show more of the class definitions
基本上我有一个像这样的模型编辑:更新以显示更多的类定义
class MyModel(Document):
dictField = DictField()
class PermHolder(Document):
meta = {'allow_inheritance': True}
....
class ValClass(PermHolder):
....
and in my code I'm trying to manipulate that dictionary using atomic updates (I had weird race condition problems before when trying normal methods and saving). 在我的代码中,我试图使用原子更新来操作该字典(在尝试常规方法和保存之前,我遇到了奇怪的竞争条件问题)。 Also, because the key is a variable I had to use kwargs as my argument into the update function
另外,因为键是变量,所以我不得不使用kwargs作为更新函数的参数
modelObject = MyModel.objects.get(id=blah)
valVar = ValClass.objects.get(id=blah)
# This works at adding the binding modelObject[keyVar] = valVar
modelObject.update(**{'set__dictField__' + keyVar: valVar })
...
# Trying to remove the binding later on
modelObject.update(**{'unset__dictField__' + keyVar: valVar })
So the second call when I try to remove gives me the error 所以当我尝试删除第二个电话给我错误
Cannot encode object: <ValClass: 51e94b55bc616310e5e4f3fb>
Which is strange because the set command worked. 这很奇怪,因为set命令起作用了。 is there another way to remove this and I'm using the incorrect syntax?
还有另一种方法可以删除此错误,而我使用的语法不正确?
如果valVar
是类的实例,并且由objectId存储-请尝试:
modelObject.update(**{'unset__dictField__' + keyVar: valVar.id })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.