简体   繁体   中英

how to combine GQL queries

So I'm making an internal messging system for my app. I need to select all messages where user is either sender or receiver.

GQL doesn't suport "OR" query so I need to run two queries, combine them (results) and then ORDER BY created DESC .

Unfortunately I can't find any docs or examples how to do that in Python.

PS.: my wild guess was db.GqlQuery("SELECT * FROM Messages WHERE sender_id = :1 ORDER BY created DESC UNION SELECT * FROM Messages WHERE receiver_id = :1 ORDER BY created DESC", user_id)

PPS.: My workaround using Python.

def get_messages(user_id):
    sender_query = db.GqlQuery("SELECT * FROM Messages WHERE sender_id = :1 ORDER BY created DESC", user_id)
    receiver_query = db.GqlQuery("SELECT * FROM Messages WHERE receiver_id = :1 ORDER BY created DESC", user_id)

    message_query = []

    for q in sender_query:
        message_query.append(q)

    for q in receiver_query:
        if q not in message_query: #doesn't work if user sent a message to himself (different instaces of same entity)
            message_query.append(q)

    message_query.sort(key=operator.attrgetter('created'))

    return message_query

Still looking for GQL-algebra-ish solution

Looks like a fine solution. App Engine DB has its limitations, it leaves a lot of work for you. I notice you are using DB; have you considered migrating to NDB? It's the next generation of DB: https://developers.google.com/appengine/docs/python/ndb/ .

NDB addresses a lot of the shortcomings of DB. For one thing, it supports "OR" queries and even nested combinations of AND and OR: https://developers.google.com/appengine/docs/python/ndb/queries#nest_and_or

If you're finding yourself spending a lot of time writing code just to do basic queries on DB, the move could be a good investment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM