Skip to main content
 首页 » 编程设计

python之[Google App Engine]如何使用filter()

2025年05月04日24Renyi-Fan

我刚开始使用 Google App Engine,我想制作类似 Twitter 的东西。

class User(db.Model): 
  account = db.StringProperty() 
  password = db.StringProperty() 
  name = db.StringProperty() 
 
class Message(db.Model): 
  user = db.ReferenceProperty() 
  text = StringProperty() 
  created = DateTimeProperty(auto_now=True) 

如何获取特定人的推文? 我试试

que = db.Query(Message).order('-created').filter("user['account'] = ",'Tom') 

但这是错误的。 我可以访问用户属性吗?

请您参考如下方法:

没有 GQL JOIN 操作。查看有关 modeling relationships 的文章对于您可以使用的其他一些技术。另外,一定要看Building Scalable, Complex Apps on App Engine ,这将非常值得您花时间。

使用您当前的模型,您需要获取用户实体(或构建其 key !)然后使用它进行查询。例如:

user = User.all(keys_only=True).filter('account', 'Tom').get()  # only get one. 
# or, build the key (if possible) 
user = db.Key.from_path('User', 'tom')  # if you make 'account' the key_name 
 
messages = Message.all().order('-created').filter("user =", user) 

另一种选择是将设计非规范化并在消息中存储“account”:

class Message(db.Model): 
  user = db.ReferenceProperty() 
  account = StringProperty() 
  text = StringProperty() 
  created = DateTimeProperty(auto_now=True) 
 
messages = Message.all().order('-created').filter("account =", 'tom')