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, blank=True,
) )
rules = None
class Meta: class Meta:
verbose_name = _("Categorisation rule") verbose_name = _("Categorisation rule")
verbose_name_plural = _("Categorisation rules") verbose_name_plural = _("Categorisation rules")
@ -1641,9 +1643,10 @@ class CategorisationRule(models.Model):
return 1 return 1
def get_category_from_rules(event): 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): if rule.match(event):
return rule.category return rule.category

View File

@ -1730,7 +1730,8 @@ def apply_categorisation_rules(request):
else: else:
# first we check if events are not correctly categorised # first we check if events are not correctly categorised
to_categorise = [] 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) c = CategorisationRule.get_category_from_rules(e)
if c and c != e.category: if c and c != e.category:
to_categorise.append((e, c)) to_categorise.append((e, c))
@ -1738,7 +1739,8 @@ def apply_categorisation_rules(request):
# then we apply rules on events without category # then we apply rules on events without category
nb = 0 nb = 0
to_save = [] 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) success = CategorisationRule.apply_rules(e)
if success: if success:
nb += 1 nb += 1