2013-02-07 14 views
0

以下哪個操作更快?django是設置操作更快還是循環?

使用for循環:

OrgIdChoices = [] 
Orgid_used_choices = [(choice["organization_id"])for choice in list(Organization.objects.all().values("organization_id"))] #Gets used ID's 
OrgIdAvailChoices = [ "%c%c" % (x, y) for x in range(ord('A'), ord('Z')+1) for y in range(ord('A'), ord('Z')+1)] #Gets available ID's 
for i in OrgIdAvailChoices: 
     if not i in Orgid_used_choices: 
      OrgIdChoices.append((i,i)) #Generates OrgIdAvailChoices which are not in Orgid_used_choices 

或使用設置操作:

OrgIdChoices = [] 
Orgid_used_choices = set([(choice["organization_id"])for choice in list(Organization.objects.all().values("organization_id"))]) 
OrgIdAvailChoices = set([ "%c%c" % (x, y) for x in range(ord('A'), ord('Z')+1) for y in range(ord('A'), ord('Z')+1)]) 
OrgChoices = OrgIdAvailChoices - Orgid_used_choices 
for i in OrgChoices: 
    OrgIdChoices.append((i,i)) 
+0

它們都比正確使用django的ORM慢。 –

+1

請您詳細說明一下嗎? – arjun

+0

檢查一個id是否在列表中或集合中是關鍵 - 其中一個比另一個更快。 – Thomas

回答

4

看一看的QuerySet API documentation,更準確地說是values_list部分(帶有flat=True)和distinct()部分。當然這會比values快,提取你想要的字段並轉換爲listset的方法。

之後,使用QuerySet生成集OrgIdAvailChoicesdifference_update的簡單方法應該比您提出的方法快得多。

另外,靈感來自Pannu的評論,這種做法與itertools

import itertools 
import string 

filter(
    lambda x: x not in OrgIdAvailChoices, 
    [''.join(el) for el in itertools.combinations_with_replacement(string.ascii_uppercase, 2)] 
) 

說實話,我不能肯定,如果QuerySet實際上是一組,即如果在它的搜索是對數,但根據我的經驗判斷,正確使用Django的ORM(如我的答案開頭所述)將爲您帶來最大的提速。

相關問題