I have this model
class Company(models.Model):
name = models.CharField(max_length = 50)
description = models.TextField()
latitude = models.FloatField()
longitude = models.FloatField()
owner = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "company_owner")
category = models.ForeignKey(Category, on_delete = models.CASCADE)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Companies"
def get_absolute_url(self):
return reverse('category_list')
#if want to redirect to its detail page then
# return reverse('company_detail' ,kwargs = {'pk' : self.pk})
def get_distance(self):
ip = get('https://api.ipify.org').text
reader = geoip2.database.Reader('categories/GeoLite2-City.mmdb')
response = reader.city(ip)
current_lat = response.location.latitude
current_lon = response.location.longitude
comp_lat = self.latitude
comp_lon = self.longitude
R = 6373.0
lat1 = radians(current_lat)
lon1 = radians(current_lon)
lat2 = radians(comp_lat)
lon2 = radians(comp_lon)
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 = R * c
return(distance)
I have got the distance between the user location and company location from get_distance() function. But how do I sort the distance in ascending order? Since the distance differs from various location of the user I can't store the distance in database. I want to print the objects sorted in ascending order by distance