pflaenz.li/pflaenzli/pflaenzli/utils/distance.py

30 lines
804 B
Python
Raw Normal View History

2023-04-05 15:34:00 +02:00
from geopy.distance import distance
import os
from pandas import read_pickle
2023-04-15 13:16:40 +02:00
from django.db.models import F, Func
2023-04-05 15:34:00 +02:00
path = os.path.dirname(os.path.abspath(__file__))
df = read_pickle(os.path.join(path, 'plz.pkl'))
def calculate_distance(zip_1, zip_2):
2023-04-09 13:07:50 +02:00
if zip_1 == zip_2:
2023-04-15 13:16:40 +02:00
return 0
2023-04-09 13:07:50 +02:00
2023-04-05 15:34:00 +02:00
zip_1_coords = tuple(df[df.index == zip_1].values)
zip_2_coords = tuple(df[df.index == zip_2].values)
2023-04-05 18:19:06 +02:00
dist = round(distance((zip_1_coords), (zip_2_coords)).kilometers)
2023-04-05 15:34:00 +02:00
return None if dist > 400 else dist
2023-04-15 13:16:40 +02:00
def filter_by_distance(qs, filter_zipcode, max_dist):
filtered_offers = []
for offer in qs:
d = calculate_distance(int(offer.zipcode), int(filter_zipcode))
if d is not None and d <= max_dist:
filtered_offers.append(offer)
return filtered_offers