编写ndb查询以与实体一起返回实体键

问题描述 投票:1回答:1

我有一个ndb用户模型:

class User(ndb.Model):
    active = ndb.BooleanProperty(default=True,required=True)
    email= ndb.StringProperty(required=True)

我为了与所有用户一起检索JSON文件而调用

@app.route('/get_users')
@login_required
def get_user_data():
    users = json.dumps([u.to_dict() for u in User.query().fetch()])
    return users

输出返回看起来像这样:

[{"email": "[email protected]"},{"email": "[email protected]"}....]

我想将每个用户的ID传递给对象,以便以后可以使用它查询单个用户。理想情况下,我希望输出看起来像这样:

[{"email": "[email protected]", "id": xxxxxx},{"email": "[email protected]", "id": xxxxxx}....]

我尝试将以下声明添加到模型类中:id = ndb.KeyProperty()

但是我得到的是空值,而不是从数据存储区实体中获取实际的ID值。

我如何拉出所有用户的密钥并将其添加到返回的对象中?

python flask google-cloud-datastore app-engine-ndb
1个回答
0
投票

您可以扩展User.to_dict以选择包括密钥:

def to_dict(self, include=None, exclude=None, include_key=False):
    d = super().to_dict(include=include, exclude=exclude)
    if include_key:
        d['key'] = self.key.urlsafe() # or some other JSON-friendly version of the key
    return d
© www.soinside.com 2019 - 2024. All rights reserved.