Query for model by key

眉间皱痕 提交于 2019-12-23 15:56:20

问题


What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:

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!

The idea is to find another User who doesn't have a partner, that isn't the user we already know.

I've tried filter('key !=, user.key()), filter('__key__ !=, user.key()) and a couple others, and nothing returns another User who doesn't have a partner. filter('foo !=, user.key()) also returns nothing, for the record.


回答1:


There's a really easy way around this: Retrieve two records, and filter out the user's own one, if it's present.

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!


来源:https://stackoverflow.com/questions/2521012/query-for-model-by-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!