我有一个 GeoDjango 项目,它有一个像这样的管理器模型;
class AdvertManager(models.GeoManager):
def within_box(self, x0, y0, x1, y1):
geometry = Polygon.from_bbox((x0, y0, x1, y1,))
return self.filter(point__within=geometry)
我试图让我的资源模型(AdvertResource)通过 GET 参数公开 inside_box 函数,例如;
http://127.0.0.1:8000/api/v1/advert/?format=json&box=51.623349,-3.25362,51.514195,-3.4754133
我开始build_filters
像这样在资源模型上写一个方法;
def build_filters(self, filters=None):
if not filters:
filters = {}
orm_filters = super(AdvertResource, self).build_filters(filters)
if 'box' in filters:
points = [float(p.strip()) for p in filters['box'].split(',')]
orm_filters = {'box': Advert.objects.within_box(*points).all()}
return orm_filters
但这会引发错误“无法将关键字'box'解析为字段......”。
是否可以将自定义管理器中的方法公开给 api url?
编辑 - 我现在已经用以下解决方案解决了这个问题。
class AdvertResource(ModelResource):
longitude = fields.FloatField(attribute='longitude', default=0.0)
latitude = fields.FloatField(attribute='latitude', default=0.0)
author = fields.ForeignKey(UserResource, 'author')
def build_filters(self, filters=None):
"""
Build additional filters
"""
if not filters:
filters = {}
orm_filters = super(AdvertResource, self).build_filters(filters)
if 'point__within_box' in filters:
points = filters['point__within_box']
points = [float(p.strip()) for p in points.split(',')]
orm_filters['within_box'] = points
return orm_filters
def apply_filters(self, request, applicable_filters):
"""
Apply the filters
"""
if 'within_box' in applicable_filters:
area = applicable_filters.pop('within_box')
poly = Polygon.from_bbox(area)
applicable_filters['point__within'] = poly
return super(AdvertResource, self).apply_filters(request,
applicable_filters)
现在这意味着请求http://127.0.0.1:8000/api/v1/advert/?format=json&point__within_box=51.623349,-3.25362,51.514195,-3.4754133
现在过滤边界框中的所有结果。