我有一些非常简单的代码:
class User(db.Document):
username = db.StringField(max_length=25)
userid = db.StringField(max_length=25)
password = db.StringField(max_length=25)
def __repr__(self):
return '<User %r>' % (self.username)
class DeviceDetails(db.Document):
profile = ReferenceField(User)
enduser = db.StringField(max_length=30, required = True)
model = db.StringField(max_length=25,required = True)
conversation = db.ListField(db.EmbeddedDocumentField('Conversation'))
def __repr__(self):
return self.enduser
class Conversation(db.EmbeddedDocument):
message = db.StringField(max_length=250)
每个用户都有一些设备详细信息,以及与每个设备详细信息相关联的一些对话。对话被附加到每个DeviceDetails上,如下所述:What is the difference between EmbeddedDocumentField and ReferenceField in mongoengine
工作正常。
现在,我希望将用户关联到DeviceDetails。我尝试添加上面“链接”中提到的代码。但出现错误:
>>> from feed.models import *
>>> d = DeviceDetails(
... profile = 'aryan',
... enduser = 'two',
... model = 'nokia'
... )
Traceback (most recent call last):
File "<console>", line 8, in <module>
File "/home/anurag/virtual/vir/lib/python2.7/site-packages/mongoengine
/base/document.py", line 85, in __init__
value = field.to_python(value)
File "/home/anurag/virtual/vir/lib/python2.7/site-packages/mongoengine/fields.py",
line 937, in to_python
value = DBRef(collection, self.document_type.id.to_python(value))
File "/home/anurag/virtual/vir/lib/python2.7/site-packages/mongoengine
/base/fields.py", line 392, in to_python
value = ObjectId(value)
File "/home/anurag/virtual/vir/lib/python2.7/site-packages/bson/objectid.py", line 90,
in __init__
self.__validate(oid)
File "/home/anurag/virtual/vir/lib/python2.7/site-packages/bson/objectid.py", line
194, in __validate
raise InvalidId("%s is not a valid ObjectId" % oid)
InvalidId: aryan is not a valid ObjectId
我在用户模型中有一些用户:
>>> User.objects.all()
[<User u'anurag'>, <User u'aryan'>]
谁能告诉我我在做什么错?
最佳答案
根据您的架构,Profile
是一个引用字段,这意味着它将存储所引用对象的ID。
您应该将其设置为User aryan的id
(或者只是将其设置为aryan用户对象),例如:
aryan = User.objects(name="aryan").first()
device = DeviceDetails(profile=aryan, enduser='two', model='nokia').save()