How to clear the table except the last N records?

There is a history table:
user
value
datetime_open

You need to remove all but the last 20 entries for each user. How to do it? Preferably ways Jangi
April 4th 20 at 13:00
2 answers
April 4th 20 at 13:02
Well, something like
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()
April 4th 20 at 13:04
I would have one SQL query is made.
DELETE FROM my_history_table t 
WHERE t.id <= (
 SELECT t2.id
 FROM my_history_table t2 
 ORDER BY DESC datetime_open
 SKIP 20
 LIMIT 1
)

Dialect of SQL to tweak to taste.

Find more questions by tags Django