Optimisation par réduction des requêtes

This commit is contained in:
Jean-Marie Favreau 2024-10-30 15:23:09 +01:00
parent fae4dbbbf2
commit 17bc54685d
2 changed files with 9 additions and 4 deletions

View File

@ -1625,6 +1625,8 @@ class CategorisationRule(models.Model):
blank=True,
)
rules = None
class Meta:
verbose_name = _("Categorisation rule")
verbose_name_plural = _("Categorisation rules")
@ -1641,9 +1643,10 @@ class CategorisationRule(models.Model):
return 1
def get_category_from_rules(event):
rules = CategorisationRule.objects.all().order_by("weight", "pk")
if CategorisationRule.rules is None:
CategorisationRule.rules = CategorisationRule.objects.all().order_by("weight", "pk").prefetch_related("category").prefetch_related("place")
for rule in rules:
for rule in CategorisationRule.rules:
if rule.match(event):
return rule.category

View File

@ -1730,7 +1730,8 @@ def apply_categorisation_rules(request):
else:
# first we check if events are not correctly categorised
to_categorise = []
for e in Event.objects.filter(start_day__gte=datetime.now()).exclude(category=Category.get_default_category_id()).exclude(category=None):
events = Event.objects.filter(start_day__gte=datetime.now()).exclude(category=Category.get_default_category_id()).exclude(category=None).prefetch_related("exact_location").prefetch_related("category")
for e in events:
c = CategorisationRule.get_category_from_rules(e)
if c and c != e.category:
to_categorise.append((e, c))
@ -1738,7 +1739,8 @@ def apply_categorisation_rules(request):
# then we apply rules on events without category
nb = 0
to_save = []
for e in Event.objects.filter(start_day__gte=datetime.now()).filter(Q(category=Category.get_default_category_id()) | Q(category=None)):
events = Event.objects.filter(start_day__gte=datetime.now()).filter(Q(category=Category.get_default_category_id()) | Q(category=None)).prefetch_related("exact_location").prefetch_related("category")
for e in events:
success = CategorisationRule.apply_rules(e)
if success:
nb += 1