Question

I have model:

from flask.ext.security import currennt_user
#instance of LocalProxy wrapped model User(db.Document)

class ContactModel(db.Document, SomeMixin):
    user = db.ReferenceField(User, verbose_name='User', required=True)

And faced strange behavior of ReferenceField. Why is working following code:

model = ContactModel(user = current_user.pk, ....)

And does not following:

model = ContactModel()
model.user = current_user.pk

The same issue when I trying to do: model = ContactModel() model.user = current_user

Last two pieaces of code throws an error: ValidationError: ValidationError (ContactModel:None) (A ReferenceField only accepts DBRef or documents: ['user'])

Was it helpful?

Solution

current_user.pk has ObjectId type (just id, no info about collection).

current_user has LocalProxy type.

You can't save reference as ObjectId because there are no information about reference collection and mongo use for this BDRef.

You can get DBRef object from mongoengine document with Document.to_dbref method.

So mognoenginge check type to get DBRef explicitly or get it from document with to_dbref.

For current_user you can call to_dbref to get DBRef object or _get_current_object() to get real User object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top