0

I want to extend Django's group model. To do so I've created a Team class, which references the group model with a OneToOne field. Create and update work as expected, but I fail to delete the team.

# teamapp/models.py
from django.db import models
from rules.contrib.models import RulesModel
from django.contrib.auth.models import Group


class Team(RulesModel):
    group = models.OneToOneField(
        Group,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    name = models.CharField(max_length=80)

    def save(self, *args, **kwargs):
        self.update_or_create_group()
        return super().save(*args, **kwargs)

    def update_or_create_group(self, *args, **kwargs):
        team_group, _ = Group.objects.update_or_create(
            id=self.pk,
            defaults={"name": self.name},
        )
        self.group = team_group
# teamapp/signals.py
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.db import transaction
from django.contrib.auth.models import Group
from teamapp.models import Team


@receiver(post_delete, sender=Team)
def delete_group(sender, instance, **kwargs):
    # TODO: Use celery for async operation: https://docs.djangoproject.com/en/3.2/topics/db/transactions/
    transaction.on_commit(lambda: delete_group(instance))


def delete_group(team_instance):
    Group.objects.filter(id=team_instance.group.id).delete()

Somehow the signal doesn't trigger. Is there an other way?

1 Answers1

0

Not sure if this is an acceptable way, but I forgot to load the signal. So I've loaded it though the apps.py file.

# teamapp/apps.py
from django.apps import AppConfig


class TeamappConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "teamapp"
    verbose_name = "Team"

    def ready(self):
        import teamapp.signals
  • Usually a `# noqa` is added to the import line, to prevent the linter from warning you that the import is never used: https://stackoverflow.com/q/45346575/67579 – Willem Van Onsem Dec 13 '21 at 19:02