2017-11-04 1 views
0

私は、Djangoの1.11にと私は私が読んだもの結合したいと思います。たとえばジャンゴ:get_querysetで条件式(自己)

オブジェクトがユーザー領域にあり、ListViewがそれを使用しているかどうかをチェックするようなものがあるとします。私はDEF(自己)get_queryset フィルタの内側に、この条件チェックを移動したい何

open_help_requests = HelpRequest.objects.filter(state=HelpRequest.OPEN) 
    filtered_help_requests = [] 
    for help_request in open_help_requests: 
     """ Formule de Haversine pour connaitre la distance entre deux points géographiques """ 
     earth_radius = 6373.0 

     lat1 = radians(help_request.student.studentcollaborator.postal_code.latitude) 
     lon1 = radians(help_request.student.studentcollaborator.postal_code.longitude) 
     lat2 = radians(request.user.student.studentcollaborator.postal_code.latitude) 
     lon2 = radians(request.user.student.studentcollaborator.postal_code.longitude) 

     dlon = lon2 - lon1 
     dlat = lat2 - lat1 

     a = sin(dlat/2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon/2) ** 2 
     c = 2 * atan2(sqrt(a), sqrt(1 - a)) 

     distance = earth_radius * c 
     if distance <= help_request.settings.distance: 
      filtered_help_requests.append(help_request) 

私は直接フィルタクエリセットと追加のシンプルなオーダー/フィルター操作を行うことができるように。フィルタリングされた変数リストのIDが重すぎるように見えるクエリセットを再作成します(このように:Django get a QuerySet from array of id's in specific order)。

アイデア?

ありがとうございました。

答えて

0

私はあなたをよく理解しているかどうかはっきりしていません。 とにかく、models.Managerのカスタムmodels.QuerySetを作成するのはどうですか?

カスタムmodels.QuerySet内では、注文/フィルタリングの目標に独自の関数を作成できます。

あなたのビューでは、あなたのオブジェクトのフィルタリング/順序付けられたリストを直接得ることができます。

class Foo(models.Model): 
    .... 
    objects = FooManager() 
    .... 

class FooManager(models.Manager): 
    .... 
    def get_queryset(self): 
     return FooQuerySet(self.model, using=self._db) 
    .... 

class FooQuerySet(models.QuerySet): 
    .... 
    # define your functions here 
    # just a simple example 
    def order(self, *args, **kwargs): 
     return self.filter(
      # you may use Q objects here or whatever 
      ).distinct() 
     else: 
      return self 
    .... 

そして、あなたのビューで:あなたの答えのための

class BarView(ListView): 
    .... 
    def get_queryset(self): 
     .... 
     return Foo.objects.all().order(params) # your custom function 
     .... 
+0

ありがとう:問題は、私はちょうどその結果に基づいてフィルタリング(パートを追加)し、別のフィルタをしたいです。各ステップでクエリーセットを再作成することは重い – jy95