import itertools
_ids = [u.histories.order_by('-datetime_open').values_list('pk', flat=True)[:20] for u in User.objects.all()]
last_20_history_ids = list(itertools.chain.from_iterable(_ids))
History.objects.exclude(pk__in=last_20_history_ids).delete()