NightSkyCode
NightSkyCode

Reputation: 1141

Receive entity by newest created first on Google App Engine

I'm using android and built my project with Google App Engine. However when I receive my list of entities they come back to me by first created. I need them to come back in the opposite direction, or just the 100 newest. I can put a limit on how many I receive actually. I cannot find anything on Google or stackoverflow. Has anyone questions or examples on this. Any quick help?

Upvotes: 0

Views: 76

Answers (2)

stevep
stevep

Reputation: 959

You will want to commit a DateProperty field with index=True and auto_now_add=True. You can then sort descending on this field with a fetch limit. There may be slicker ways, but this is my tried and true.

IMHO - it is a very good idea to always include this date_created property on every important entity. Whether or not you index it is depends on its use. As noted by Tomasz, entity ids - while generally ascending - are not guaranteed to be so. DO NOT rely on them. So if you ever find yourself needing to progress sequentially though your model, you will be very happy to have your "datec" field. (Also a good idea to always include a "version" IntegerProperty on every record which proves very useful whenever you need to read/write your way through existing entities to ensure a recent property change is applied to them all.) Given these potential benefits, ask yourself what the costs are that would keep you from ending each model with these two properties. {Note: indexing is a real cost, so do not set index=True from these fields unless you plan to use it.)

datec = ndb.DateTimeProperty(indexed=True, auto_now_add=True)
v = ndb.IntegerProperty(indexed=False, default=1)

Upvotes: 1

StanislavL
StanislavL

Reputation: 57421

You can add ORDER BY id DESC and LIMIT to your query

Upvotes: 1

Related Questions