Django查询每次迭代都命中数据库 [英] Django query hitting the db for every iteration
问题描述
我有一些像这样的 model.py :
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 以获得唯一的标本,并找到所有共享该分类单元的标本。对于相关的标本,我只需要纬度/经度信息:
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)
但是当我循环遍历 related_specimens
时,它最终会为每个<$ c $一次命中数据库c>相对。我是否应该仅通过一个额外的数据库查询就可以获取所需格式的 latitudedecimal
和 longitudedecimal
值?我知道我在这里的方法中缺少一些非常基本的东西,只是不确定能做到这一点的最佳方法。
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.
任何帮助将不胜感激。
推荐答案
只需使用选择相关:
related_specimens = Muestraonline.objects.filter(taxonid=specimen.taxonid).exclude(id=specimen.id).select_related('muestraid')
这将把您的 Muestraonline
模型加入到 Muestra
的幕后,以及每个 Muestraonline $ QuerySet返回的c $ c>实例还将包含
Muestra
的缓存实例。
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
.
这篇关于Django查询每次迭代都命中数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!