S
S
semolex2014-12-01 16:55:45
MongoDB
semolex, 2014-12-01 16:55:45

How to get Reference Field from MongoDB using Flas\MongEngine?

Hello!
There is a problem:
With the help of MongoEngine, I created a "scheme" of documents:

class Users(Document):
    login = fields.StringField(unique=True, max_length=25, primary_key=True, required=True)
    books = fields.ListField(fields.ReferenceField('Books'), default=["No favorites"])

and
class Books(Document):
    title = fields.StringField(required=True)
    author = fields.StringField()


Now, using Flask, I've done the following:
@app.route('/users/<id>', methods=['GET'])
def edit_user(id):
    user = Users.objects(login=id)
    books = [Books.objects(id__in=user[0].books)]
    return user.to_json(), books.to_json()

All is well, as long as I try to "get" only user. When I try to retrieve the books (ReferenceField) object, I get the following error:
ValidationError: Books object is not a valid ObjectId

I want all objects with all the attributes referenced by the books field in the Users object.
How to me to draw out objects which lie in ReferenceField?
How to make a request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
_
_ _, 2014-12-01
@AMar4enko

Um, I’m not boom-boom in Python, especially in MongoEngine, but by analogy with other systems, user[0].books will return your books to you by independently executing the request that you are trying to execute by id manually.

V
Vitaly F., 2015-01-20
@FuN_ViT

Judging by the documentation, you need to do:
and the books field will be filled with objects...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question