def _distinct_action_time(query, limit=None):
    """
    Distinct rows by the 'action_time' field, keeping in the query only the
    entry with the highest 'id' for the related set of entries with equal
    'action_time'.

    If 'limit' is set, the function  will return the 'limit'-most-recent
    actionlogs.

    Example:

        For the following query set:

            id |          action_time
            ----+----------------------------
            1 | 2010-03-11 10:55:26.32941-03
            2 | 2010-03-11 10:55:26.32941-03
            3 | 2010-03-11 13:48:22.202596-09
            4 | 2010-03-11 13:48:53.505697-03
            5 | 2010-03-11 13:48:53.505697-03
            6 | 2010-03-11 13:51:09.013079-05
            7 | 2010-03-11 13:51:09.013079-05
            8 | 2010-03-11 13:51:09.013079-05

        After passing through this function the query will be:

            id |          action_time
            ----+----------------------------
            2 | 2010-03-11 10:55:26.32941-03
            3 | 2010-03-11 13:48:22.202596-09
            5 | 2010-03-11 13:48:53.505697-03
            8 | 2010-03-11 13:51:09.013079-05

        Rows with the same 'action_time' are eliminated, keeping the one with
        highest 'id'.
    """
    pks = query.defer('object_id', 'content_type').distinct()
    if limit:
        pks = pks.order_by('-id')[:limit]
    else:
        # For some reason, when using defer() the Meta ordering
        # is not respected so we have to set it explicitly.
        pks = pks.order_by('-action_time')
    return pks.select_related('user')