我使用this link和this link编写了以下代码,以查询在我的一个分支机构半径内的企业。
from django.db.models import Func, F
from li_app.models import Branch, Business
class Sin(Func):
function = 'SIN'
class Cos(Func):
function = 'COS'
class Acos(Func):
function = 'ACOS'
class Radians(Func):
function = 'RADIANS'
class Degrees(Func):
function = 'DEGREES'
def filter_within_distance(
branch_kwargs,
business_kwargs,
radius
):
KM_PER_DEGREE = 111.045
branch = Branch.objects.filter(**branch_kwargs)[0]
lat_point = branch.branch_latitude
long_point = branch.branch_longitude
radlat = Radians(lat_point)
radlong = Radians(long_point)
radflat = Radians(F('business_latitude'))
radflong = Radians(F('business_longitude'))
Expression = KM_PER_DEGREE * Degrees(Acos(Cos(radlat) * Cos(radflat) *
Cos(radflong - radlong) + Sin(radlat) * Sin(radflat)))
latitude_delta = radius / KM_PER_DEGREE
longitude_delta = radius / (KM_PER_DEGREE * Cos(radlat))
lat_range = (float(lat_point) - latitude_delta, float(lat_point) + latitude_delta)
long_range = (float(long_point) - longitude_delta, float(long_point) + longitude_delta)
business_kwargs['business_latitude__range'] = lat_range
business_kwargs['business_longitude__range'] = long_range
return Business.objects.filter(**business_kwargs).annotate(distance=Expression).filter(distance__lte=radius).order_by('distance')
现在,我想修改上面的查询,以使所有公司都在我所有分支机构的半径范围内。我想避免python循环,因此,如果有任何方法可以在查询中执行循环,那将非常棒。