InvalidDocument:无法编码对象:<用户:用户对象>带有 MongoEngine 的 ReferenceField [英] InvalidDocument: Cannot encode object: <User: User object> ReferenceField with MongoEngine
问题描述
我一直在使用 Flask 和 MongoEngine,但由于 ReferenceField,我在尝试保存对象时遇到了问题.
I've been working with Flask and MongoEngine, and I am having trouble when trying to save an object because of a ReferenceField.
这是我的模型的样子:
class User(UserMixin, db.Document):
first_name = db.StringField(max_length=255, required=True)
last_name = db.StringField(max_length=255, required=True)
email = db.StringField(max_length=255)
class Post(db.Document):
description = db.StringField(max_length=255, required=True)
inserted_at = db.DateTimeField(default=datetime.datetime.now, required=True)
tags = db.ListField(db.EmbeddedDocumentField('Tag'))
comments = db.ListField(db.EmbeddedDocumentField('Comment'))
user = db.ReferenceField('User')
这是我创建 Post 对象的方式:
This is how I create the Post object:
user = User.objects.filter(id=current_user.id).first()
post = Post(
description = request.json["description"],
user = user
)
我也试过:
user = current_user._get_current_object()
但我不断收到:
InvalidDocument: Cannot encode object: <User: User object>
对正在发生的事情有什么想法吗?
Any ideas on what's going on?
谢谢!
推荐答案
嗯,这是很久以前的问题了,但我遇到了同样的问题.我不知道是不是出于不同的原因,但上下文看起来确实非常相似.
Well, this is from a long time, but I got the same problem. I don't know if it's for different reasons, but the context does look very similar.
无论如何,看起来 current_user
对象是一个 LocalProxy
实例,它不能很好地与 mongoengine 配合使用.诀窍是强制"取消引用实例的 ObjectID,如下所示:
Anyway, it looks like the current_user
object is a LocalProxy
instance which does not play well with mongoengine. The trick was to "force" dereference the ObjectID of the instance, like this:
post = Post(
description = request.json["description"],
user = user.id
)
这篇关于InvalidDocument:无法编码对象:&lt;用户:用户对象>带有 MongoEngine 的 ReferenceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!