Hi, Could you please look at this situation where I try to deal with adding ForeignKey relation at runtime and using it in a annotate construct? Is this code illustrates a bug in Django or am I trying to do something illegal here? I'm using Django 1.1.
--- <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.) [] (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> --- -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.