mysql - Why 2 queries are executed instead of one? -


i have following piece of code:

def detail(request, popular_id):    try:       popular = popular.objects.get(pk = popular_id)       share = share.objects.get(isin = popular.isin) #line 1       chart_data_json = share.get_chart_data_json()    except popular.doesnotexist:       raise http404    return render(request, 'popular/detail.html', {'popular': popular, 'chart_data': chart_data_json}) 

in line 1 noticed using debug-toolbar there 2 queries executed:

select `share_share`.`id`, `share_share`.`symbol`, `share_share`.`isin`, `share_share`.`name`, `share_share`.`market`, `share_share`.`updated` `share_share` `share_share`.`id` = 1 

and

select `share_share`.`id`, `share_share`.`symbol`, `share_share`.`isin`, `share_share`.`name`, `share_share`.`market`, `share_share`.`updated` `share_share` `share_share`.`isin` = 'us5949181045' 

i cannot understand why need first query , how avoid it?

edit:

model definition of share:

class share(models.model):    symbol = models.charfield(max_length = 32)    isin = models.charfield(max_length = 12)    name = models.charfield(max_length = 256)    market = models.charfield(max_length = 64)    updated = models.booleanfield(default = false)     def get_chart_data_json(self):       quote_model = create_quote_model(str(self.isin))       data = quote_model.objects.values('date', 'adj_close', 'volume')       chart_data = []       d in data.iterator():          chart_data.append({'date': d['date'].isoformat(), 'value': d['adj_close'], 'volume': d['volume']})       chart_data_json = json.dumps(chart_data)       return chart_data_json     def __unicode__(self):       return self.isin 

model definition of popular:

class popular(models.model):    title = models.charfield(max_length = 120)    text = models.charfield(max_length = 1024)    isin = models.foreignkey(share)     def __unicode__(self):       return self.title 

  1. first query evaluated when access foreign key isin popular object:

    share = share.objects.get(isin = popular.isin)

  2. second query gets share object:

    share = share.objects.get(isin = popular.isin)

if want 1 query @ #line 1 should replace with:

share = popular.isin #line 1 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -