Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #14081: Fix cached counters on delete for parent-child items #14131

Merged
merged 2 commits into from
Dec 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions netbox/utilities/counters.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.apps import apps
from django.db.models import F, Count, OuterRef, Subquery
from django.db.models.signals import post_delete, post_save
from django.db.models.signals import post_delete, post_save, pre_delete

from netbox.registry import registry
from .fields import CounterCacheField
Expand Down Expand Up @@ -62,6 +62,12 @@ def post_save_receiver(sender, instance, created, **kwargs):
update_counter(parent_model, new_pk, counter_name, 1)


def pre_delete_receiver(sender, instance, origin, **kwargs):
model = instance._meta.model
if not model.objects.filter(pk=instance.pk).exists():
instance._previously_removed = True


def post_delete_receiver(sender, instance, origin, **kwargs):
"""
Update counter fields on related objects when a TrackingModelMixin subclass is deleted.
Expand All @@ -71,10 +77,8 @@ def post_delete_receiver(sender, instance, origin, **kwargs):
parent_pk = getattr(instance, field_name, None)

# Decrement the parent's counter by one
if parent_pk is not None:
# MPTT sends two delete signals for child elements so guard against multiple decrements
if not origin or origin == instance:
update_counter(parent_model, parent_pk, counter_name, -1)
if parent_pk is not None and not hasattr(instance, "_previously_removed"):
update_counter(parent_model, parent_pk, counter_name, -1)


#
Expand Down Expand Up @@ -106,6 +110,12 @@ def connect_counters(*models):
weak=False,
dispatch_uid=f'{model._meta.label}.{field.name}'
)
pre_delete.connect(
pre_delete_receiver,
sender=to_model,
weak=False,
dispatch_uid=f'{model._meta.label}.{field.name}'
)
post_delete.connect(
post_delete_receiver,
sender=to_model,
Expand Down