如何显示GAE查询对象的内容和结构?

0 投票
1 回答
705 浏览
提问于 2025-04-16 14:12

我想打印出一个查询对象的结构,类似于在Python交互式提示符下打印字典或列表的内容。我发现我很难想象这些数据结构的样子,这当然让传递模板参数变得更加困难。

举个例子,这里有一个非常简单的用户资料数据库类,我尝试打印出所有的用户资料,以及第二个用户资料的内容。

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app

class UserProfile(db.Model):
    user = db.UserProperty(auto_current_user_add=True)
    name = db.StringProperty()

class TestHandlerBasic(webapp.RequestHandler):
    def get(self):
        profiles = UserProfile.all()
        self.response.out.write('The whole profiles: ')
        self.response.out.write(profiles)
        self.response.out.write('<p>')
        self.response.out.write('Now, print out all profiles: <p>')
        for profile in profiles:
            self.response.out.write(profile.user)
            self.response.out.write('<br>')
        self.response.out.write('<p>')
        self.response.out.write('There are this many profiles: ')
        self.response.out.write(profiles.count())
        self.response.out.write('<p>This is the second profile profiles[1]: ')
        self.response.out.write(profiles[1])
        return

application = webapp.WSGIApplication([(r'/testbasic', TestHandlerBasic),] debug=True)

我得到这样的输出:

所有用户资料:

现在,打印出所有用户资料:

test@example.com
ard@example.com

用户资料总共有: 2

这是第二个用户资料 profiles[1]:

在第一行之后,我得到了 <google.appengine.ext.db.Query object at 0x490bd10>,最后一行我也得到了 <models.UserProfile object at 0x490bb90>。那么,我该如何打印出查询对象或模型对象的详细信息呢?

1 个回答

3

查询对象本身并不保存任何数据库模型(db.Model)实体,它们是通过 get()fetch() 方法返回的。所以你需要把 UserProfile.all() 替换成类似下面的东西:

profiles = UserProfile.all().fetch(1000)

我个人喜欢从 db.Model 类继承,给我的模型添加一些方便的功能,以便于序列化我的模型。这样做主要是为了能快速得到实体的 JSON 表示,但这对于导出或检查它们也很有用。

下面是我扩展的 BaseModel 的一个例子,它为实体添加了 __dict____json__ 方法。如果你再添加一个 __repr__ 方法来输出 __dict__ 的内容,就能在控制台打印实体时改善它们的字符串表示。

撰写回答