2017-08-08 63 views
0

所以我目前正在試圖改善代碼的項目。使用for或if循環過濾

目前,我有這個作爲我的views.py

def home1(request): 
    if request.user.is_authenticated(): 


     location = request.GET.get('location', request.user.profile.location) 
     users = User.objects.filter(profile__location=location) 
     print users 

     matchesper = Match.objects.get_matches_with_percent(request.user) 
     print matchesper 

     matches = [match for match in matchesper if match[0] in users][:20] 

目前,用戶給我回的是具有相同的位置request.user和matchesper給了我一個匹配百分比與所有的用戶列表用戶。然後匹配使用這兩個列表來給我一個用戶名單與他們的匹配百分比,並與request.users位置

這工作完美,但儘快使用該網站的用戶數量增加這將變得非常慢?例如,我可以在匹配器末尾添加[:50],但這意味着您將永遠不會與具有與request.user相同位置的舊用戶匹配。

我的問題是,是否沒有辦法只爲具有相同位置的用戶創建與匹配器的匹配?我可以在匹配器或for循環之前使用if語句嗎?

我還沒有寫這段代碼,但是我明白了,但是當試圖改進它的時候,我很困難,希望我的解釋和問題是有道理的。

感謝您提前給予任何幫助我很困難!

+0

你可以在這裏使用'__in'。但是,目前還不清楚你的管理器方法get_matches_with_percent是如何工作的或者返回的。 –

回答

1

(我假設你正在使用的matchmaker project

在Django中,你可以chain QuerySet methods。你會注意到你正在使用的models.py文件同時定義了一個MatchQuerySet和一個MatchManager。您可能還注意到get_matches_with_percent僅在Manager上定義,而不是在QuerySet上定義。

這是一個問題,但不是一個不可逾越的問題。解決它的一個辦法是修改我們的管理器方法實際工作的QuerySet。我們可以通過創建一個基本上是get_matches_with_percent副本的新方法來完成此操作,但需要進行一些額外的過濾。

class MatchManager(models.Manager): 

[...] 

    def get_matches_with_percent_by_location(self, user, location=None): 
     if location is None: 
      location = user.profile.location 
     user_a = Q(user_a__profile__location=location) 
     user_b = Q(user_b__profile__location=location) 
     qs = self.get_queryset().filter(user_a | user_b).matches(user).order_by('-match_decimal') 
     matches = [] 
     for match in qs: 
      if match.user_a == user: 
       items_wanted = [match.user_b, match.get_percent] 
       matches.append(items_wanted) 
      elif match.user_b == user: 
       items_wanted = [match.user_a, match.get_percent] 
       matches.append(items_wanted) 
      else: 
       pass 
     return matches 

注意在第10行中使用重複鏈接!這是魔法。

其他說明:

  • Q objects是做複雜的查詢,比如多個 「或」 條件的一種方式。
  • 一個更好的解決方案將分解出共有的get_matches_with_percentget_matches_with_percent_by_location保持代碼的「幹」的元素,但是這是現在不夠好;)
  • 要留意的是,get_matches_with_percent返回香草列表而不是Django QuerySet;這是一個「終端」方法。因此,在調用get_matches_with_percent後,您不能使用任何其他QuerySet方法(如filter)。
+0

非常感謝您的幫助!然而,我現在得到這個問題,AttributeError在/ 'MatchQuerySet'對象沒有屬性'get_matches_with_percent' – caldf

+0

在匹配應用程序models.py你可以找到MatchQuerySet,任何想法?對不起,這樣的滋擾 – caldf

+0

啊。如果你看看L.29,你會發現'MatchesManager'是一個'Manager',而不是一個QuerySet。所以一旦你調用'filter',它的方法就不可用了。我會用不同的解決方案修改我的答案... – pbaranay