문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top