I am in Django 1.11 and I would like to combine what I read:
- https://docs.djangoproject.com/fr/1.11/ref/models/conditional-expressions/
- https://docs.djangoproject.com/fr/1.11/topics/class-based-views/generic-display/
- https://docs.djangoproject.com/fr/1.11/ref/models/querysets/#django.db.models.Q
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.