Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duplicate Results for ManyToMany field with DistanceToPointFilter #103

Open
egamonal opened this issue Apr 1, 2016 · 2 comments
Open

Duplicate Results for ManyToMany field with DistanceToPointFilter #103

egamonal opened this issue Apr 1, 2016 · 2 comments

Comments

@egamonal
Copy link

egamonal commented Apr 1, 2016

A year ago a similar issue was filled for Django framework encode/django-rest-framework#1488

Model example:


class PointOfSales(models.Model):
    location = models_gis.PointField(blank=True, null=True)

class Deal(models.Model):
    promo_code = models.CharField(max_length=25, blank=True, null=True)
    points_of_sales = models.ManyToManyField(PointOfSales, related_name='deals')

I wanted to filter deals in points of sales near me:

class DealViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = DealSerializer
    queryset = Deal.objects.all()
    filter_backends = (DistanceToPointFilter, )
    distance_filter_field = 'points_of_sales__location'
    distance_filter_convert_meters = True # by default we use srid=4326 (uses degrees), but input should be in meters

A deal in two points of sales near me will end up twice in the response.

In /rest_framework_gis/filters.py there is a filter_queryset method where I added .distinct() just like in the PR that fixed restframework encode/django-rest-framework@3522b69 and I got the expected result. I didn't break any other of my tests. Might it be a fix?

    def filter_queryset(self, request, queryset, view):
        # ...
        return queryset.filter(Q(**{'%s__%s' % (filter_field, geoDjango_filter): (point, dist)})).distinct()
@egamonal
Copy link
Author

egamonal commented Apr 1, 2016

In the meantime I extended the class in my filters.pymodule

from rest_framework_gis.filters import DistanceToPointFilter


class DistanceToPointFilterDistinct(DistanceToPointFilter):
    def filter_queryset(self, request, queryset, view):
        return super(DistanceToPointFilterDistinct, self).filter_queryset(request, queryset, view).distinct()

@nemesifier
Copy link
Member

Thanks for publishing your solution @egamonal.
I'm not sure your solution can be applied as the general default case. Let's leave this issue open so if other people will encounter a similar problem we can continue the discussion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants