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)
我已经从get_distance()函数中获取了用户位置和公司位置之间的距离。但是如何按升序排序这些距离呢?由于距离会因用户的不同位置而异,所以我不能将距离存储在数据库中。我想打印按距离升序排序的对象。