python - 按键查询模型

标签 python google-app-engine google-cloud-datastore

我想做的是在数据存储中查询一个模型,其中的键不是我已经拥有的对象的键。这是一些代码:

class User(db.Model):
    partner = db.SelfReferenceProperty()

def text_message(self, msg):
    user = User.get_or_insert(msg.sender)

    if not user.partner:
        # user doesn't have a partner, find them one
        # BUG: this line returns 'user' himself... :(
        other = db.Query(User).filter('partner =', None).get()
        if other:
            # connect users
        else:
            # no one to connect to!

我们的想法是找到另一个没有合作伙伴的 User,这不是我们已知的用户。

我试过filter('key !=, user.key()), filter('__key__ !=, user.key()) 和一个与其他人配对,没有任何内容会返回另一个没有合作伙伴的 Userfilter('foo !=, user.key()) 也没有返回任何内容,以供记录。

最佳答案

有一个非常简单的方法解决这个问题:检索两条记录,并过滤掉用户自己的记录(如果存在)。

def text_message(self, msg):
    user = User.get_or_insert(msg.sender)

    if not user.partner:
        # user doesn't have a partner, find them one
        other = db.Query(User).filter('partner =', None).fetch(2)
        other = [u for u in other if u.key() != user.key()]
        if other:
            # connect user with other[0]
        else:
            # no one to connect to!

关于python - 按键查询模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2521012/

相关文章:

python - bs4 如何提取 <p> 标签中的文本

google-app-engine - 后端 "Process moved to a different machine"并因错误 500 而失败

java - Google App 引擎 memcached 设计

google-app-engine - Google Cloud SDK 中对 google-auth 的依赖性错误?

python - 如何在 Google App Engine 中使用 python 从我们要在 ndb 数据存储中搜索的元素列表中进行 AND & OR 运算查询

python - 无法使用存储过程pyodbc SQL SERVER 创建数据库

python - 按 X 列对数据框进行分组

python - 在 Pandas DataFrame 中选择包含至少一个 True 值的列的最佳解决方案

python - 尝试在 Google App Engine 网站上加载 Ace.js 编辑器会导致格式错误的路径错误

python - 谷歌云端点: Picturesque App