Sort on DateIndex

In an addon package that I am developing for Plone 5, I would like to sort content based on a field called "upload_time" which is of type zope.schema.Datetime. I have added an index for it, in the catalog.xml as follows:

<index name="upload_time" meta_type="DateIndex">
    <indexed_attr value="upload_time"/>
</index>

How can I sort the content objects based on this field(like most recent to oldest) ?

If you have upload time as index / meta_data you can add a smart folder and set sort on to "upload_time".

1 Like

creating a smart folder helped in creating a collection of content objects that are sorted.

But, I'd like to get a list of such content objects to be used in a custom view template (like brains returned by catalog). I have two such lists created as follows:

return api.content.find(
context=self.context,
depth=1,
portal_type='AddOn',
blacklisted=False,
sort_on='download_sum_total',
sort_order='reverse'
)

and

return api.content.find(
context=self.context,
depth=1,
portal_type='AddOn',
curated=True,
sort_on='sortable_title',
sort_order='ascending'
)

Here, both sortable_title and download_sum_tota were field indexes. Does the same method apply for DateIndex as well?

To be able to sort via an index, this index must be very much "field index" like. It would, e.g., not work with a KeywordIndex or a TextIndex (because, an object may have more than a single value and therefore, may have more positions in the order). A DateIndex is quite like a FieldIndex (but not derived from it); it might be possible to use it in a sort (try it out).

Should it not work, you can use the same approach as for title/sortable_title, i.e. define a second index (this time a FieldIndex) alongside your DateIntex and use it for sorting.

Technical note: in order to be able to use an index for sorting, the index must provide the interface Products.PluginIndexes.interfaces.ISortIndex. This suggests the following alternative to the above index pair approach: use monkey patching to enhance the DateIndex by this interface. A DateIndex is sufficiently near to a FieldIndex, that it can use its implementation for this interface.

1 Like

The other thing I do is look through existing Plone code for examples. Things that sort items by date: e.g. how does a collection do it, or how does the recently_modified view do it, or how does folder_contents view does it?