문제

I have some pretty simple code:

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)

where every user will have some device details and some conversation linked to every device detail. The conversation is being appended to every DeviceDetails as mentioned here: What is the difference between EmbeddedDocumentField and ReferenceField in mongoengine which is working fine.

Now I wish to associated a user to DeviceDetails. I tried adding the code mentioned in the "link" above. but got a error:

>>> 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

I have some users in User model:

>>> User.objects.all()
[<User u'anurag'>, <User u'aryan'>]

Can anyone tell me what I am doing wrong here?

도움이 되었습니까?

해결책

According to your schema Profile is a reference field, which means it will store the id of the object it references.

You should set it to be the id of the User aryan (or just set it to be the aryan user object) eg:

aryan = User.objects(name="aryan").first()
device = DeviceDetails(profile=aryan, enduser='two', model='nokia').save()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top