﻿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
14177	Out of date cache on django.db.models.options.Options instance after adding ForeignKey at runtime	anonymous	nobody	"{{{
--- <bash session> --- 
localhost:~$ django-admin.py startproject dbg 
localhost:~$ cd dbg/ 
localhost:~/dbg$ python manage.py startapp myapp 
localhost:~/dbg$ echo ""from django.db import models 
class SomeObject(models.Model): 
    title = models.TextField()
 
class SomeItem(models.Model): 
    someint = models.IntegerField()"" > myapp/models.py 
localhost:~/dbg$ echo ""from myapp.models import * 
try: 
    SomeObject.objects.annotate(models.Avg('items__someint')) 
except Exception as e: 
    print e, '(Obviously, because relation to items is not defined)' 

SomeItem.add_to_class('object', models.ForeignKey(SomeObject, related_name='items')) 

try: 
    SomeObject.objects.annotate(models.Avg('items__someint')) 
except Exception as e: 
    print e, \""(Doesn't work because cache in SomeObject._meta is not updated after SomeItem.add_to_class call.)\"" 

print 'It seems that forcing cache on SomeObject._meta to reload fixes the problem.'
del SomeObject._meta._name_map 
del SomeObject._meta._related_objects_cache 
print SomeObject.objects.annotate(models.Avg('items__someint')), '(Working!)' 

from django.db import connection 

print connection.queries[-1]['sql']"" > test.py 
localhost:~/dbg$ export DJANGO_SETTINGS_MODULE=""settings"" 
localhost:~/dbg$ sed -i s/""DATABASE_ENGINE.*""/""DATABASE_ENGINE = 'sqlite3'""/g settings.py 
localhost:~/dbg$ sed -i s/""DATABASE_NAME.*""/""DATABASE_NAME = 'db'""/g settings.py 
localhost:~/dbg$ python ./test.py 
Cannot resolve keyword 'items' into field. Choices are: id, title 
(Obviously, because relation to items is not defined) 
Cannot resolve keyword 'items' into field. Choices are: id, title 
(Doesn't work because cache in SomeObject._meta is not updated after SomeItem.add_to_class call.) 
It seems that forcing cache on SomeObject._meta to reload fixes the problem.
[] (Working!) 
SELECT ""myapp_someobject"".""id"", ""myapp_someobject"".""title"", 
AVG(""myapp_someitem"".""someint"") AS ""items__someint__avg"" FROM 
""myapp_someobject"" LEFT OUTER JOIN ""myapp_someitem"" ON 
(""myapp_someobject"".""id"" = ""myapp_someitem"".""object_id"") GROUP BY 
""myapp_someobject"".""id"", ""myapp_someobject"".""title"" LIMIT 21 
--- </bash session> ---
}}}
 "		closed	Database layer (models, ORM)	1.1		duplicate			Unreviewed	0	0	0	0	0	0
