hd_riqi
hd_riqi

Reputation: 37

Google app engine - Order listed item

I need your help to order listed item. I am trying to make apps that can send message to his/her friends ( just like social feeds ). After watching Bret Slatkin talk about create microblogging here's my code:

class Message(ndb.Model):
    content = ndb.TextProperty()
    created = ndb.DateTimeProperty(auto_now=True)

class MessageIndex(ndb.Model):
    receivers = ndb.StringProperty(repeated=True)

class BlogPage(Handler):
    def get(self):
        if self.request.cookies.get("name"):
            user_loggedin = self.request.cookies.get("name")
        else:
            user_loggedin = None

        receive = MessageIndex.query(MessageIndex.receivers == user_loggedin)
        receive = receive.fetch()

        message_key = [int(r.key.parent().id()) for r in receive]

        messages = [Message.get_by_id(int(m)) for m in message_key]

        for message in messages:
            self.write(message)

The first I do a query to get all message that has my name in the receivers. MessageIndex is child of Message, then I can get key of all message that I receive. And the last is I iter get_by_id using list of message key that I get.

This works fine, but I want to filter each message by its created datetime and thats the problem. The final output is listed item, which cant be ordered using .order or .filter

Maybe some of you can light me up.

Upvotes: 1

Views: 78

Answers (1)

ChrisC73
ChrisC73

Reputation: 1853

You can use the message keys in an 'IN' clause in the Message query. Note that you will need to use the parent() key value, not the id() in this case.

eg:

# dtStart, dtEnd are datetime values
message_keys = [r.key.parent() for r in receive]
query = Message.query(Message._key.IN(message_keys), Message.created>dtStart, Message.created<dtEnd)
query = query.order(Message.created) # or -Message.created for desc
messages = query.fetch()

I am unsure if you wish to simply order by the Message created date, or whether you wish to filter using the date. Both options are catered for above.

Upvotes: 2

Related Questions