gpt4 book ai didi

django - 将我自己的查询参数添加到 django admin

转载 作者:行者123 更新时间:2023-12-02 08:09:14 25 4
gpt4 key购买 nike

我有一个使用纬度和经度字段作为位置的模型。我想要使​​用查询参数运行的查询之一是围绕特定半径进行搜索。我读取了查询集并覆盖它:

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 会优雅地发生 panic 并重定向不过滤的管理页面。

我能做什么?

最佳答案

您应该从请求中弹出客户参数。试试这个:

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

关于django - 将我自己的查询参数添加到 django admin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46959243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com