2014-04-07 92 views
1

我有下面這段代碼:爲什麼執行2個查詢而不是1個?

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}) 

第1行中我使用調試工具欄裏注意到有兩個查詢得到執行:

SELECT `share_share`.`id`, `share_share`.`symbol`, `share_share`.`isin`, `share_share`.`name`, `share_share`.`market`, `share_share`.`updated` FROM `share_share` WHERE `share_share`.`id` = 1 

SELECT `share_share`.`id`, `share_share`.`symbol`, `share_share`.`isin`, `share_share`.`name`, `share_share`.`market`, `share_share`.`updated` FROM `share_share` WHERE `share_share`.`isin` = 'US5949181045' 

我不能理解爲什麼我們需要第一個查詢以及如何避免它?

編輯:份額的

模型定義:流行

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 = [] 
     for 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 

模型定義:

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

你能提供圖片熱門和共享的ide模型定義? –

+0

向帖子添加了模型定義。 – NST

回答

1
  1. 當您訪問外鍵從流行的對象ISIN

    首先查詢評估:

    份額= Share.objects.get(ISIN = popular.isin

  2. 第二查詢獲取分享對象:

    份額= Share.objects.get(ISIN = popular.isin)

如果你想在#行1只是一個查詢,你應該將其替換爲:

share = popular.isin #LINE 1 
相關問題