python - mongoengine 引用字段 mongoengine.errors.ValidationError

标签 python flask mongoengine flask-login

需要你的帮助。我尝试使用 mongoengine、flask、flask-login。

我的模型:

class Post(db.Document):
   text = db.StringField(max_length=240)
   pub_date = db.DateTimeField(default=datetime.datetime.now)
   author = db.ReferenceField(Member)

然后我得到当前用户(flask-login):

from flask.ext.login import current_user

比在 views.py 中:

new_post = Post()
    new_post.text = 'bla-bla'
    #new_post.author = current_user                                 #- DON`T WORK
    new_post.author = Member.objects.get(id=current_user.id)        #-WORK (WHY?)
    new_post.save()

new_post.author = current_user 如果 new_post.author = Member.objects.get(id=current_user.id) 有什么问题 - 工作正常。

如果尝试使用 new_post.author = current_user - 得到错误:

mongoengine.errors.ValidationError
ValidationError: ValidationError (Post:None) (A ReferenceField only accepts DBRef or documents: ['author'])

谢谢大家。

最佳答案

这些错误的发生是因为 current_userLocalProxy类型,而 mongo 正在寻找引用。同时 current_user在许多方面与实际的工作方式相同 Member它代理的对象,它不能用作引用,因为没有关于 mongo 用作 DBRef 的引用集合的信息。

如果您想避免 Member.objects.get(id=current_user.id) 获取实际对象,您可以直接获取实际的 Member来自 current_user 的对象:

new_post.author = current_user._get_current_object()

或者只是 DBRef :

new_post.author = current_user.to_dbref()

关于python - mongoengine 引用字段 mongoengine.errors.ValidationError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21244415/

相关文章:

python - 使用 Cronjob 更改数据窗口(在 MAC 上)

python - Flask 中的 Thread Local Objects 是什么意思?

python - 作者:美丽汤。我想将 <br> 替换为换行符 : At the time of getText()

python - 与词法作用域和 for 循环作斗争

python - 用 Flask 重写 URL

python - 使用 Flask 将多个按钮点击附加到列表中

python - 你在 MongoDB 中使用数据映射器吗?

python - 如何在mongoengine中按oid搜索文档

python - Flask 应用程序无法在 dockerized 设置中使用 mongoengine 从 mongodb 查询数据

python - python属性查找过程如何工作?