V
V
vhsporno2020-01-20 15:26:13
Django
vhsporno, 2020-01-20 15:26:13

How to clear a table except for the last N records?

There is a history table:
user
value
datetime_open
It is necessary to delete all but the last 20 records for each user. How to do it? Preferably in djanga ways

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim Shatalov, 2020-01-20
@netpastor

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()

S
Sergey Pankov, 2020-01-21
@trapwalker

I would do it with one SQL query.

DELETE FROM my_history_table t 
WHERE t.id <= (
    SELECT t2.id
    FROM my_history_table t2 
    ORDER BY datetime_open DESC
    SKIP 20
    LIMIT 1
)

Correct the SQL dialect to taste.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question