Skip to content

Commit d2f075f

Browse files
committed
clear cache on new request
1 parent 229e408 commit d2f075f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

netbox_custom_objects/models.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from django.db import connection, IntegrityError, models, transaction
1616
from django.db.models import Q
1717
from django.db.models.functions import Lower
18+
from django.core.signals import request_started
1819
from django.db.models.signals import pre_delete, post_save
1920
from django.dispatch import receiver
2021
from django.urls import reverse
@@ -1601,3 +1602,46 @@ class CustomObjectObjectType(ObjectType):
16011602

16021603
class Meta:
16031604
proxy = True
1605+
1606+
1607+
# Signal handlers to clear model cache when definitions change
1608+
1609+
1610+
@receiver(request_started)
1611+
def clear_cache_on_request(sender, **kwargs):
1612+
"""
1613+
Clear the model cache at the start of each request.
1614+
1615+
The cache is not a performance cache, it is a recursion prevention cache,
1616+
mainly for __init__ get_models() and get_model() methods. This makes
1617+
sure that each request will have a fresh model cache.
1618+
"""
1619+
CustomObjectType.clear_model_cache()
1620+
1621+
1622+
@receiver(post_save, sender=CustomObjectType)
1623+
def clear_cache_on_custom_object_type_save(sender, instance, **kwargs):
1624+
"""
1625+
Clear the model cache when a CustomObjectType is saved.
1626+
"""
1627+
CustomObjectType.clear_model_cache(instance.id)
1628+
1629+
1630+
@receiver(post_save, sender=CustomObjectTypeField)
1631+
def clear_cache_on_field_save(sender, instance, **kwargs):
1632+
"""
1633+
Clear the model cache when a CustomObjectTypeField is saved.
1634+
This ensures the parent CustomObjectType's model is regenerated.
1635+
"""
1636+
if instance.custom_object_type_id:
1637+
CustomObjectType.clear_model_cache(instance.custom_object_type_id)
1638+
1639+
1640+
@receiver(pre_delete, sender=CustomObjectTypeField)
1641+
def clear_cache_on_field_delete(sender, instance, **kwargs):
1642+
"""
1643+
Clear the model cache when a CustomObjectTypeField is deleted.
1644+
This is in addition to the manual clear in the delete() method.
1645+
"""
1646+
if instance.custom_object_type_id:
1647+
CustomObjectType.clear_model_cache(instance.custom_object_type_id)

0 commit comments

Comments
 (0)