2
分贝我有一些model.py像这样:Django的查询命中每次迭代
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.
...
而且我view.py我想要得到的唯一样本,发现其中分享所有的标本该生物分类。对于相关标本我需要的只是经/纬信息:
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)
但是,当我遍历related_specimens
它最终击中分贝一次为每个relative
。我不应该只用一个额外的数据库查询就能得到我需要的格式的latitudedecimal
和longitudedecimal
值吗?我知道我在这里忽略了一些非常基本的东西,只是不确定完成这件事的最佳方式。
任何帮助将不胜感激。
完全正确!我完全忘记了'select_related' - 已经有一段时间了,因为我有打电话来使用它。谢谢。 – 2012-04-21 00:23:17