ale*_*nov 5 python mongodb mongoengine
我有一些非常简单的代码:
from mongoengine import *
class Comment(Document):
id = IntField(primary_key=True)
text = StringField()
class Message(Document):
id = IntField(primary_key=True)
comments = ListField(ReferenceField(Comment))
connect('test_db')
c1 = Comment(id=1)
c1.text = 'message_one'
c1.save()
c2 = Comment(id=2)
c2.text = 'message_two'
c2.save()
m = Message(id=1)
m.comments = [c1, c2]
m.save()
msg = Message.objects.get(id=1)
for comment in msg.comments:
print comment.id, comment.text
Run Code Online (Sandbox Code Playgroud)
我期望它将打印
1个message_one
2个message_two
但是我有
1个message_one
1个message_one
当我使用任何mongodb管理界面查看数据库时,一切似乎都正常:
{“ _cls”:“消息”,“ _id”:1,“ _types”:[“消息”],
“ comments”:[{{“ $ ref”:“ comment”,“ $ id”:1},{“ $ ref”:“ comment”,“ $ id”:2}]}
我试图在代码中交换c1和c2(例如,使用m.comments = [c2,c1]),但出乎意料的是,我得到了正确的输出:
2个message_two
1个message_one
另外,我尝试不使用自定义主键“ id”,并且在两种情况下都可以正常工作。
我对此错误感到非常困惑,似乎mongoengine出了点问题,或者我没有正确使用它。拜托,有什么想法吗?