Model representation with FK, exceeding queries

21 views
Skip to first unread message

Cleiton Lima

unread,
May 12, 2017, 1:03:23 PM5/12/17
to Django users
I do not know if it is a bug or has already been commented

# models.py
class State(models.Model):
    name
= models.CharField(_('name'), max_length=60)


   
class Meta:
        verbose_name
= _('state')
        verbose_name_plural
= _('states')


   
def __str__(self):
       
return self.name

class City(models.Model):
    name
= models.CharField(_('name'), max_length=60)
    state
= models.ForeignKey('State', verbose_name=_('state'), related_name='cities')


   
class Meta:
        verbose_name
= _('city')
        verbose_name_plural
= _('cities')


   
def __str__(self):
       
return '{} - {}'.format(self.name, self.state.name)

# forms.py
class AnythingForm(forms.ModelForm):
   
class Meta:
        model
= Anything
        fields
= ['city']

# template.html
{{form.city}}

I have 5565 records in model City.

Django==1.11.1 execute 5565 queries to render select
Django==1.10.7 only 2

If replace return '{} - {}'.format(self.name, self.state.name) to self.name in __str__ of city model, it works. 

Is this really a problem or my mistake?

Simon Charette

unread,
May 12, 2017, 1:32:35 PM5/12/17
to Django users
Hello Cleiton,

I'm a bit surprised only two queries were executed on 1.10 as each
time a city string representation is created the associated state
will need to be fetched as well.

Were you using any form of select_related()/prefetch_related() to make
sure this wasn't an issue? It's possible that the template based widget
rendering introduced in 1.11 broke your optimization somehow that would
be an actual bug.

Simon

Cleiton Lima

unread,
May 15, 2017, 9:58:49 AM5/15/17
to Django users
I just found the problem. The plugin I use to render this select is breaking in django 1.11.
I really did not see this problem.
Reply all
Reply to author
Forward
0 new messages