Adds a background task to remove StockItem objects which are scheduled for deletion

This commit is contained in:
Oliver 2021-09-07 16:45:58 +10:00
parent 7d3cd03d6c
commit 918106c225
3 changed files with 50 additions and 3 deletions

View File

@ -63,6 +63,13 @@ class InvenTreeConfig(AppConfig):
schedule_type=Schedule.DAILY,
)
# Delete "old" stock items
InvenTree.tasks.schedule_task(
'stock.tasks.delete_old_stock_items',
schedule_type=Schedule.MINUTES,
minutes=30,
)
def update_exchange_rates(self):
"""
Update exchange rates each time the server is started, *if*:

View File

@ -216,6 +216,11 @@ class StockItem(MPTTModel):
# A query filter which can be used to filter StockItem objects which have expired
EXPIRED_FILTER = IN_STOCK_FILTER & ~Q(expiry_date=None) & Q(expiry_date__lt=datetime.now().date())
def mark_for_deletion(self):
self.scheduled_for_deletion = True
self.save()
def save(self, *args, **kwargs):
"""
Save this StockItem to the database. Performs a number of checks:
@ -1300,10 +1305,10 @@ class StockItem(MPTTModel):
self.quantity = quantity
if quantity == 0 and self.delete_on_deplete and self.can_delete():
# TODO - Do not actually "delete" stock at this point - instead give it a "DELETED" flag
self.delete()
if quantity == 0 and self.delete_on_deplete and self.can_delete():
self.mark_for_deletion()
return False
else:
self.save()

35
InvenTree/stock/tasks.py Normal file
View File

@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from django.core.exceptions import AppRegistryNotReady
logger = logging.getLogger('inventree')
def delete_old_stock_items():
"""
This function removes StockItem objects which have been marked for deletion.
Bulk "delete" operations for database entries with foreign-key relationships
can be pretty expensive, and thus can "block" the UI for a period of time.
Thus, instead of immediately deleting multiple StockItems, some UI actions
simply mark each StockItem as "scheduled for deletion".
The background worker then manually deletes these at a later stage
"""
try:
from stock.models import StockItem
except AppRegistryNotReady:
logger.info("Could not delete scheduled StockItems - AppRegistryNotReady")
return
items = StockItem.objects.filter(scheduled_for_deletion=True)
logger.info(f"Removing {items.count()} StockItem objects scheduled for deletion")
items.delete()