问题
I have a some model.py like so:
class Muestraonline(models.Model):
accessionnumber = models.ForeignKey(Muestra, related_name='online_accessionnumber')
muestraid = models.ForeignKey(Muestra)
taxonid = models.ForeignKey(Taxon, null=True, blank=True)
...
class Muestra(models.Model):
muestraid = models.IntegerField(primary_key=True, db_column='MuestraID') # Field name made lowercase.
latitudedecimal = models.DecimalField(decimal_places=6, null=True, max_digits=20, db_column='LatitudeDecimal', blank=True) # Field name made lowercase.
longitudedecimal = models.DecimalField(decimal_places=6, null=True, max_digits=20, db_column='LongitudeDecimal', blank=True) # Field name made lowercase.
...
And my view.py I want to get the unique specimen and find all specimens which share that taxonid. For the related specimens I just need the lat/long info:
def specimen_detail(request, accession_number=None, specimen_id=None):
specimen = Muestraonline.objects.get(accessionnumber=accession_number, muestraid=specimen_id)
related_specimens = Muestraonline.objects.filter(taxonid=specimen.taxonid).exclude(id=specimen.id)
# create array for the related specimen points
related_coords = []
# loop through results and populate array
for relative in related_specimens:
latlon = (format(relative.muestraid.latitudedecimal), format(relative.muestraid.longitudedecimal))
related_coords.append(latlon)
related_coords = simplejson.dumps(related_coords)
But when I loop through related_specimens
it ends up hitting the db once for each relative
. Shouldn't I be able to get the latitudedecimal
and longitudedecimal
values in the format I need with only one extra db query? I know I missing something very basic in my approach here, just not sure of the best way to get this done.
Any help would be much appreciated.
回答1:
Just use select_related in your QuerySet:
related_specimens = Muestraonline.objects.filter(taxonid=specimen.taxonid).exclude(id=specimen.id).select_related('muestraid')
That will join your Muestraonline
model to Muestra
behind the scenes and each Muestraonline
instance returned by the QuerySet will also contain a cached instance of Muestra
.
来源:https://stackoverflow.com/questions/10255011/django-query-hitting-the-db-for-every-iteration