我有一个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值。
我如何拉出所有用户的密钥并将其添加到返回的对象中?
您可以扩展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