Jason Hall
Jason Hall

Reputation: 20920

Query for model by key

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.

Upvotes: 4

Views: 395

Answers (1)

Nick Johnson
Nick Johnson

Reputation: 101139

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!

Upvotes: 4

Related Questions