2015-03-19 77 views
0

我目前正在優化我的一些項目中的代碼,並發現一些非常慢的代碼。我有一個通過Django查詢獲得的對象列表。我想過濾這個列表並只返回一個對象,因爲這些值是唯一的。從Django模型對象列表中過濾對象的最佳方法

questions = set(Question.object.all()) 
choices = set(Choice.objects.select_related('question').filter(question__in=questions).all()) 

for question in questions: 
    Answer(question=question, 
      choice=next(filter(lambda x: x.question == question), choices)), 
      response=response) 

其中一些只是僞代碼,但真正的問題是在next()函數中。有沒有更快的方法來查找一組中的元素?使用列表理解是無可爭議的,因爲它解析整個列表並返回所有元素。 Filter是一個生成器,next()返回它找到的第一個值。

我使用Django 1.7和Python 3.4

謝謝!

回答

1

我不會在這裏使用一個集合,而是使用由問題ID鍵入的字典。 (請注意,您實際上並不需要此問題,因此您可以刪除select_related。)

choice_dict = {c.question_id: c for c in Choice.objects.filter(question__in=questions).all()} 
for question in questions: 
    Answer(question=question, 
      choice=choice_dict[question.id], 
      response=response) 
+0

謝謝!加快了很多。 – 2015-03-19 12:28:17