|
9 | 9 | import click |
10 | 10 | from datetime import datetime, timedelta |
11 | 11 |
|
12 | | -from boards.models import Article |
| 12 | +from django.conf import settings |
13 | 13 |
|
14 | | - |
15 | | -DEFAULT_CLEANUP_DAYS = 300 |
| 14 | +from boards.models import Article, BoardFeed |
16 | 15 |
|
17 | 16 |
|
18 | 17 | @click.command() |
19 | | -@click.option('--older-than-days', default=DEFAULT_CLEANUP_DAYS, help="Num days to cleanup older articles") |
20 | | -def cleanup(older_than_days): |
| 18 | +@click.option( |
| 19 | + '--older-than-days', |
| 20 | + default=settings.OLD_ARTICLES_CLEANUP_AFTER_DAYS, |
| 21 | + help="Num days to cleanup older articles" |
| 22 | +) |
| 23 | +@click.option( |
| 24 | + '--more-than-amount', |
| 25 | + default=settings.OLD_ARTICLES_CLEANUP_AFTER_AMOUNT, |
| 26 | + help="Max amount of articles allowed in feed" |
| 27 | +) |
| 28 | +def cleanup(older_than_days, more_than_amount): |
| 29 | + click.echo(f"Cleaning up articles older than {older_than_days} days...") |
21 | 30 | Article.objects.filter(created_at__lte=datetime.utcnow() - timedelta(days=older_than_days)).delete() |
| 31 | + for feed in BoardFeed.objects.all(): |
| 32 | + click.echo(f"Cleaning up feed {feed.name}, leaving {more_than_amount} last articles...") |
| 33 | + last_article_to_leave = Article.objects\ |
| 34 | + .filter(feed=feed)\ |
| 35 | + .order_by("created_at")[more_than_amount:more_than_amount + 1].first() |
| 36 | + if last_article_to_leave: |
| 37 | + num_deleted, _ = Article.objects.filter(feed=feed, created_at__gt=last_article_to_leave.created_at).delete() |
| 38 | + click.echo(f"Deleted {num_deleted} old articles!") |
| 39 | + click.echo("Done") |
22 | 40 |
|
23 | 41 |
|
24 | 42 | if __name__ == '__main__': |
|
0 commit comments