按距离过滤对象

时间:2020-05-12 20:06:32

标签: django geodjango

我正在研究一个将新场所添加到数据库时通知用户的代码。用户最多可以保存3个自定义过滤器,我想通知他们有关仅与其过滤器匹配的新地点。假设我有以下模型:

class Address(models.Model):
    country = models.ForeignKey(...)
    post_code = models.CharField(...)
    city = models.CharField(...)
    location = models.PointField()


class Place(models.Model):
    name = ...
    type = ...
    something = ...
    address = models.ForeignKey(Address, ...)


class UserFilter(models.Model):
    name = ...
    type = ...
    something = ...
    location = models.PointField()
    distance = models.DecimalField(...)

API允许使用请求参数过滤Place查询集。用户只能发送latlongdistance参数来获得给定范围内的位置:

distance = float(request.query_params.get('distance', None))
ref_location = Point(
    float(request.query_params.get('lat', None)),
    float(request.query_params.get('long', None))
)
filters &= Q(address__location__distance_lte=(ref_location, D(km=distance)))

但是现在,当我创建一个新的Place时,我想过滤UserFilter查询集以找到location(包括distance)“覆盖”新的过滤器Place个位置。问题是distance是我要过滤的模型中的一个字段。有解决这个问题的灵巧方法吗?

0 个答案:

没有答案