I have a couple of models: Review
, which has fields for album reviews, Record
, which is an album's name etc, and Band
, which is a band's name. Record
has a foreign key against Band
and Review
has a foreign key against Record
.
In the admin forms for Review
I want to show a dropdown select box for all Record
s. At the moment, the unicode method for Record
is just:
def __unicode__(self):
return self.record_name
This isn't very helpful so I changed it to this:
def __unicode__(self):
return self.band.band_name + ' - ' + self.record_name
This now adds a query for each Record
(3000 or so), obviously not good.
Reading this answer, I tried adding this to my model admin for Record
:
def queryset(self, request):
return super(RecordAdmin, self).queryset(request).select_related('band')
This didn't make any difference, though.
Is it possible to use foreign key fields in the __unicode__
representation of a model without incurring n-squared queries?
UPDATE: here's the models (with unrelated fields removed):
class Review(models.Model):
def __unicode__(self):
# this is used in other places where we show review titles
return self.record.band.band_name + ' - ' + self.record.record_name
record = models.ForeignKey('Record')
review_text = models.TextField()
class Record(models.Model):
def __unicode__(self):
# this generates a billion queries
#return self.record_name
return self.band.band_name + ' - ' + self.record_name
def band_and_title(self):
return self.band.band_name + ' - ' + self.record_name
band = models.ForeignKey('Band')
label = models.ForeignKey('Label')
record_name = models.CharField(max_length=175)
class Band(models.Model):
def __unicode__(self):
return self.band_name
band_name = models.CharField(max_length=100)