Skip to content

Commit

Permalink
feat(follows): delete object-orphaned Follows...
Browse files Browse the repository at this point in the history
... based on Django pre_delete signal
  • Loading branch information
David-Guillot authored and auvipy committed Mar 31, 2023
1 parent b894d76 commit d06e7e2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions actstream/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.apps import apps
from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import pre_delete

from actstream import settings as actstream_settings
from actstream.signals import action
Expand All @@ -25,3 +26,6 @@ def ready(self):
DataField(blank=True, null=True).contribute_to_class(
action_class, 'data'
)

from actstream.follows import delete_orphaned_follows
pre_delete.connect(delete_orphaned_follows)
16 changes: 16 additions & 0 deletions actstream/follows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.core.exceptions import ImproperlyConfigured

from actstream.models import Follow


def delete_orphaned_follows(sender, instance=None, **kwargs):
"""
Clean up Follow objects that refer to a Django object that's being deleted
"""
if str(sender._meta) == 'migrations.migration':
return

try:
Follow.objects.for_object(instance).delete()
except ImproperlyConfigured: # raised by actstream for irrelevant models
pass
5 changes: 4 additions & 1 deletion actstream/tests/test_activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,10 @@ def test_following_models_OR_query(self):
def test_y_no_orphaned_follows(self):
follows = Follow.objects.count()
self.user2.delete()
self.assertEqual(follows - 1, Follow.objects.count())
# 2 Follow objects are deleted:
# * "User2 follows group" because of the on_delete=models.CASCADE
# * "User1 follows User2" because of the pre_delete signal
self.assertEqual(follows - 2, Follow.objects.count())

def test_z_no_orphaned_actions(self):
actions = self.user1.actor_actions.count()
Expand Down

0 comments on commit d06e7e2

Please sign in to comment.