【问题标题】:Add my own query parameters to django admin将我自己的查询参数添加到 django admin
【发布时间】:2017-11-17 16:56:49
【问题描述】:

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

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 会优雅地恐慌并重定向一个未过滤的管理页面。

我能做什么?

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    您应该从请求中弹出自定义参数。试试这个:

    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 会删除任何不属于模型的参数。 “半径”不是模型的一部分
    • 我刚刚解决了同样的问题。我尝试传递不属于模型的查询参数(number),并重定向到 /applabel/users/?e=1。我添加了代码,我在上面写过,它的工作。我刷新页面 url:/applabel/users/?number=5,并得到正确的结果(按 number 过滤)。 (Django1.11)
    • 一旦我弹出自定义参数,而管理页面加载正常并且更多自定义列表(基于查询参数可见),当我单击以通过管理过滤器排序列或过滤器时,查询参数不会持久化(并且它的效果会丢失)。我们该如何解决?
    猜你喜欢
    • 2020-07-19
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2022-12-04
    相关资源
    最近更新 更多