Simplified, I have 2 Document objects: Resource
and Cable
class Cable(db.Document):
_id = db.ObjectIdField()
socket = db.EmbeddedDocumentField(Socket)
class Resource(db.Document):
_id = db.StringField()
cable = db.ReferenceField('Cable')
Both the documents are already in the db, but the cable field in the resource is set to null
.
@resources.route('/<r_id>/add_cabling', methods=['GET'])
def set_connector(r_id):
r = Resource.objects(id=r_id).get()
c = Cable.objects().first()
r.cable=c
r.save()
return jsonify(r)
So I am passing the instance of the document Cable
to the instance of Resource
and then save()
. The error that I get is the following:
ValidationError: ValidationError (Resource:res01) (A ReferenceField only accepts DBRef or documents: ['cable'])
I don't understand because actually I am passing the document itself
Tried with this workaround passing the DBRef
of the document and it works.
@resources.route('/<r_id>/add_cabling', methods=['GET'])
def set_connector(r_id):
r = Resource.objects(id=r_id).get()
c = Cable.objects().first()
c.save() #revalidate here
r.cable=c.to_dbref()
r.save()
return jsonify(r)
It is necessary to perform the save()
operation again on the queried object to get the DBRef
otherwise it will throw this error:
OperationError: Only saved documents can have a valid dbref
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.