我有一个使用纬度和经度字段进行定位的模型。我想使用查询参数运行的查询之一是围绕特定半径进行搜索。我有查询集读取,我覆盖它:
queryset = super().get_queryset(request)
if 'radius' in request.GET:
queryset = queryset.in_distance(request.GET['radius'], fields=['location__latitude',location__longitude'], points=[lat, lon])
return queryset
使用/admin/dal/listing?radius=50
调用我的管理页面时,我会被重定向到没有查询字符串的管理员。
跟随Django的代码,发现了这个:
# At this point, all the parameters used by the various ListFilters
# have been removed from lookup_params, which now only contains other
# parameters passed via the query string. We now loop through the
# remaining parameters both to ensure that all the parameters are valid
# fields and to determine if at least one of them needs distinct(). If
# the lookup parameters aren't real fields, then bail out.
try:
for key, value in lookup_params.items():
lookup_params[key] = prepare_lookup_value(key, value)
use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, key)
return filter_specs, bool(filter_specs), lookup_params, use_distinct
except FieldDoesNotExist as e:
six.reraise(IncorrectLookupParameters, IncorrectLookupParameters(e), sys.exc_info()[2])
简而言之,因为查询字符串不是已知字段,django会优雅地恐慌并重定向非过滤器管理页面。
我该怎么办?
答案 0 :(得分:5)
您应该从请求中弹出自定义参数。试试这个:
def get_queryset(self, request):
queryset = super().get_queryset(request)
request.GET = request.GET.copy()
radius = request.GET.pop('radius', None)
if radius:
queryset = queryset.in_distance(
radius[0], fields=['location__latitude', 'location__longitude'],
points=[lat, lon])
return queryset