Opened 9 minutes ago
#37509 new Bug
FETCH_PEERS: GenericForeignKey returns a stale object after changing object_id or content_type
| Reported by: | Akshat Gupta | Owned by: | |
|---|---|---|---|
| Component: | contrib.contenttypes | Version: | 6.1 |
| Severity: | Normal | Keywords: | fetch modes, FETCH_PEERS |
| Cc: | Akshat Gupta | Triage Stage: | Unreviewed |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
With FETCH_PEERS, a GenericForeignKey keeps returning the old object after its object_id or content_type changes.
Models:
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, models.CASCADE) class Tag(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey()
alice = Author.objects.create(name="Alice") bob = Author.objects.create(name="Bob") Tag.objects.create(content_object=alice) Tag.objects.create(content_object=alice) tag1, tag2 = Tag.objects.fetch_mode(FETCH_PEERS).order_by("pk") tag1.content_object tag1.object_id = bob.pk tag1.content_object.name
This returns 'Alice'. With FETCH_ONE it returns 'Bob'.
Changing the content type is worse. After setting tag1.content_type to Book and tag1.object_id to a book's pk, tag1.content_object still returns the Author, an object of the wrong model.
Cause: GenericForeignKeyDescriptor.__get__() sees that the cached object no longer matches, but it doesn't clear the cache before calling fetch(). fetch_many() skips every instance that has a cached value, including this one, so nothing is fetched and the stale object is returned.
Clearing the cache with self.field.delete_cached_value(instance) before fetching fixes it. I can submit a patch with a test if this is accepted.