Skip to content

Model.get_cached() cache is not invalidated on ForeignKey update from on_delete #3

@philipkimmey

Description

@philipkimmey

Let's say I have a Person object with a ForeignKey to a default image.

class Person(models.Model):
    default_image = models.ForeignKey('people.Image', blank=True, null=True,
         on_delete=models.SET_NULL)

class Image(models.Model):
    some_image_field = models.ImageField(...)

>>> p = Person.objects.get(first_name='Phil')
>>> img = Image.objects.get(**some_kwargs)
>>> p_cached = Person.get_cached(pk=p.pk)
>>> p.default_image = img
>>> p.save()
>>> p_cached = Person.get_cached(pk=p.pk)
>>> p.default_image is not None
True
>>> p_cached.default_image is not None
True
>>> img.delete()
>>> p.default_image is None
True
>>> p_cached = Person.get_cached(pk=p.pk)
>>> p_cached.default_image is None
Traceback (most recent call last)
...
File "django/db/models/fields/related.py", line 316, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
DoesNotExist: Image matching query does not exist.

It's a pretty tricky bug, and it may be nearly impossible to fix if the on_delete actually sets a database property that leads to that behavior rather than doing it in Python.

Nonetheless, I felt I should probably report it just so it's a known issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions