﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37509	FETCH_PEERS: GenericForeignKey returns a stale object after changing object_id or content_type	Akshat Gupta		"With `FETCH_PEERS`, a `GenericForeignKey` keeps returning the old object after its `object_id` or `content_type` changes.

Models:

{{{#!python
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()
}}}

{{{#!python
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.
"	Bug	new	contrib.contenttypes	6.1	Normal		fetch modes, FETCH_PEERS	Akshat Gupta	Unreviewed	0	0	0	0	0	0
