0

I am in Django 1.11 and I would like to combine what I read:

For example, suppose I have something like this that will check if Objects are in the user area and a ListView use it.

    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)

What I want to move this condition check inside the filter in def get_queryset(self): so that I could directly make additional simple order/filter operations with the filtered QuerySet. Recreate the QuerySet with the filtered variable list id looks too heavy (like this : Django get a QuerySet from array of id's in specific order).

Any ideas ?

Thanks.

jy95
  • 773
  • 13
  • 36

1 Answers1

0

Quite not sure that I'm understanding you well. Anyway,what about creating custom models.QuerySet for your models models.Manager?

Inside your custom models.QuerySet you can create your own functions for your ordering/filtering goals.

And in your view you can directly get your filtered/ordered list of your objects.

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
    ....

And in your view:

class BarView(ListView):
    ....
    def get_queryset(self):
        ....
        return Foo.objects.all().order(params) # your custom function
        ....
catscoolzhyk
  • 675
  • 10
  • 29
  • Thanks for your answer : the problem is I just want to filter based on the result (append part) and do another filters . Recreate the queryset at each step is heavy – jy95 Nov 05 '17 at 11:38