Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add my own query parameters to django admin

I have a model that uses latitude and longitude fields for location. One of the queries that I want to run using query params is search around a specific radius. I have the queryset read and I override it:

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

When calling my admin page with /admin/dal/listing?radius=50 I get redirected to the admin without the query string.

Followed Django's code and found this:

# 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])

In a nutshell because the query string is not a known field django gracefully panics and redirect a not filter admin page.

What can I do ?

like image 900
Efi MK Avatar asked Oct 26 '17 16:10

Efi MK


1 Answers

You should pop custome parameters from request. Try this:

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
like image 144
Nikita Isaev Avatar answered Nov 15 '22 04:11

Nikita Isaev