I have the following models:
class Territory(models.Model):
name = models.CharField(max_length=30)
power = models.ForeignKey(Power, null=True, blank=True)
is_supply = models.BooleanField()
class Subregion(models.Model):
territory = models.ForeignKey(Territory)
subname = models.CharField(max_length=10, blank=True)
sr_type = models.CharField(max_length=1, choices=SUBREGION_CHOICES)
init_unit = models.BooleanField()
borders = models.ManyToManyField("self", null=True, blank=True)
def __unicode__(self):
if self.subname:
return u'%s (%s)' % (self.territory.name, self.subname)
else:
return u'%s [%s]' % (self.territory.name, self.sr_type)
The problem is that when rendering a ModelFormSet
, each form of which has 3 ModelChoiceFields
containing all 120 Subregions
, an individual SELECT
query is generated for each Subregion
in each widget. According to my Postgres logs, over 1000 queries are being generated for a simple 3-form formset, with a noticeable effect on page load times.
So, is there a reasonable way to do a single large query that will cache all of the information that Subregion.__unicode__()
wants?