Nithish Albin
Nithish Albin

Reputation: 362

how to get mongoengine object id in flask program

i am using mongoengine to integrate with flask , i wanted to know how to get document object id every time i try i get File "/var/www/flask_projects/iot_mongo/app.py", line 244, in post return jsonify(user.id) AttributeError: 'BaseQuerySet' object has no attribute 'id'

class Test(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('email',required=True, help='email')
        args=parser.parse_args()
        user=AdminUser.objects(email=args['email'])
        return jsonify(user.id)
api.add_resource(Test,'/test')

if __name__ == '__main__':
    app.run(debug=True) 

Upvotes: 3

Views: 10688

Answers (2)

Joseph Vargas
Joseph Vargas

Reputation: 792

I've been doing this. An example User model would be like~

class User(Document):
    first_name = StringField(required=True, max_length=50)
    last_name = StringField(required=True, max_length=50)
    username = StringField(required=True)
    password = StringField(required=True, min_length=6)

    def to_json(self):
        return {
            "_id": str(self.pk),
            "first_name": self.first_name,
            "last_name": self.last_name,
            "username": self.username,
            "password": self.password
        }

I convert the id to a string. I would then get a single object with~

user = User.objects.get(pk=user_id)
return user.to_json()

for a whole object, but if I just want the id I would do...

user.pk()

I created my own to_json method that converts the primary key to a string because otherwise it would return "id": ObjectID("SomeID") instead of neatly printing "id": "SomeID". Hope this helps! If you want to find someone by email I suggest~

User.objects.get(email=args['email'])

Upvotes: 5

bgse
bgse

Reputation: 8587

Check out the documentation, Document.objects is a QuerySet object.

You seem to be expecting that this part of your code

user=AdminUser.objects(email=args['email']) # user will be a QuerySet

will give you a single result, which is not the case, it will give you a QuerySet with zero or more results. It does not have an attribute id, this is why you get the error message you are seeing when you try to access this attribute here:

return jsonify(user.id) # QuerySet does not have the attribute id

You need to fetch the actual result(s) you want from it, assuming you are sure your query will return a single result, or do not care that there might be more than one result and just want the first one, you probably want something along these lines:

user=AdminUser.objects(email=args['email']).first() # extract first result
return jsonfiy(user)

Alernatively, returning all results would look like this:

users=AdminUser.objects(email=args['email']).all() # extract all results
return jsonfiy(users)

Upvotes: 3

Related Questions