【发布时间】:2012-07-16 14:47:12
【问题描述】:
我有一些非常简单的代码:
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
我预计它会打印出来
1 message_one
2 message_two
但我有
1 message_one
1 message_one
当我使用任何 mongodb 管理 UI 来查看数据库时,一切似乎都正常:
{ "_cls" : "消息" , "_id" : 1 , "_types" : [ "消息"] ,
"cmets" : [ { "$ref" : "comment" , "$id" : 1} , { "$ref" : "comment" , "$id" : 2}]}
我尝试在代码中交换 c1 和 c2(例如使用 m.cmets = [c2, c1]),但出乎意料的是,我得到了正确的输出:
2 message_two
1 message_one
我也尝试不使用自定义主键“id”,并且在这两种情况下一切正常。
我对这个错误很困惑,似乎是 mongoengine 有问题,或者我没有以正确的方式使用它。请问有什么想法吗?
【问题讨论】:
标签: python mongodb mongoengine