Skip to content

M2M querysets not being invalidated on instance deletion #407

Description

@tumb1er

We have a model with a non-autoincremental primary key, which has an m2m relation.

After deleting and creating an instance with same primary keys, we are getting stale m2m cache.
This is mostly because of Django not sending m2m_changed on instance deletion (see https://code.djangoproject.com/ticket/17688).

I'll add a PR with a failing test later, but have no good decision of fixing this on the cacheops side. Also, the bug was very difficult to catch, lots of conditions must be satisfied, so I'd like to propose to add a workaround for Django on the cacheops side.

class Profile(Model):
   user = OneToOneField(User, CASCADE, primary_key=True)
   roles = ManyToManyField(Role, blank=True)

user = User.objects.create()
profile = Profile.objects.create(user=user)
role = Role.objects.create()

profile.roles.set([role])

assert len(list(profile.roles.all())) == 1

profile.delete()  # Here m2m relation is not invalidated

profile = Profile.objects.create(user=user)

assert len(list(profile.roles.all())) == 0  # Assertion fails

# Workaround

@receiver(pre_delete, sender=Profile)
def invalidate_m2m_after_delete(sender, instance, **kwargs):
    invalidate_dict(Profile.roles.through, {'profile_id': instance.pk})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions