保存参考字段mongoengine [英] Save reference field mongoengine

查看:76
本文介绍了保存参考字段mongoengine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简化了,我有2个Document对象: Resource Cable

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

两个文档都已经在数据库中,但是资源中的电缆字段设置为 null .

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)

因此,我将文档 Cable 的实例传递给 Resource 的实例,然后传递给 save().我收到的错误如下:

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)(ReferenceField仅接受DBRef或文档:['cable'])

ValidationError: ValidationError (Resource:res01) (A ReferenceField only accepts DBRef or documents: ['cable'])

我不明白,因为实际上我正在传递文档本身

I don't understand because actually I am passing the document itself

推荐答案

通过传递文档的 DBRef 的这种解决方法进行了尝试,并且可以正常工作.

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)

有必要在查询的对象上再次执行 save()操作以获取 DBRef ,否则将引发此错误:

It is necessary to perform the save() operation again on the queried object to get the DBRef otherwise it will throw this error:

OperationError:仅保存的文档可以具有有效的dbref

OperationError: Only saved documents can have a valid dbref

这篇关于保存参考字段mongoengine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆