|
15 | 15 | from django.db import connection, IntegrityError, models, transaction |
16 | 16 | from django.db.models import Q |
17 | 17 | from django.db.models.functions import Lower |
| 18 | +from django.core.signals import request_started |
18 | 19 | from django.db.models.signals import pre_delete, post_save |
19 | 20 | from django.dispatch import receiver |
20 | 21 | from django.urls import reverse |
@@ -1601,3 +1602,46 @@ class CustomObjectObjectType(ObjectType): |
1601 | 1602 |
|
1602 | 1603 | class Meta: |
1603 | 1604 | 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