ForeignKey in Inline generates lots of queries

103 views
Skip to first unread message

john....@plushrugs.com

unread,
Feb 20, 2014, 5:45:27 PM2/20/14
to django-d...@googlegroups.com
I posted this to Django users, but didn't get a response. I'd like to help to resolve this issue if at all possible.

Previous post:

I have the Django admin configured with a TabularInline, and the inline model has a ForeignKey reference to a third model. Every row in the inline generates a new query to fetch all of the instances of the third model.

Here's an overview of my code:

# models.py
from django.db import models

class ExampleParent(models.Model):
   
    def __unicode__(self):
        return u'Example Parent: %s' % self.id

class ExampleInline(models.Model):
    parent = models.ForeignKey('ExampleParent')
    child = models.ForeignKey('ExampleChild')
   
    def __unicode__(self):
        return u'Example Inline: %s' % self.id
   
class ExampleChild(models.Model):
   
    def __unicode__(self):
        return u'Example Child: %s' % self.id

# admin.py
from django.contrib import admin

from admin_issue.example_problem.models import (ExampleParent, ExampleInline)

class ExampleInlineInline(admin.TabularInline):
    model = ExampleInline

class ExampleParentAdmin(admin.ModelAdmin):
    inlines = [
        ExampleInlineInline
    ]

admin.site.register(ExampleParent, ExampleParentAdmin)

If you create a bunch of ExampleInlines that reference and ExampleParent, then go to that instance in the admin, you get QUERY = u'SELECT "example_problem_examplechild"."id" FROM "example_problem_examplechild"' - PARAMS = () for every ExampleInline referenced.

Shouldn't that query be cached by Django? Is that expected behavior? Is there a way to force Django to use the cache for subsequent inlines?

I'm also experiencing a similar problem with a ManyToMany field. (But it seems to generate even more queries that the ForeignKey)

Any help on this issue would be most appreciated.

Thanks,

John P.

Tim Graham

unread,
Feb 21, 2014, 7:15:26 AM2/21/14
to django-d...@googlegroups.com
Hi John,

django-developers is for discussion of the development of Django itself. It isn't a second level support channel if your query on django-users goes unanswered. Thanks!
Reply all
Reply to author
Forward
0 new messages