philipn/django-rest-framework-filters

How to distinct result?

AsheKR opened this issue · 3 comments

/api/posts/?comment__content='some contnet' has more than one same post id

image

how can i distinct this result?

  • pip list
    django: 2.2.9
    django-filter: 2.2.0
    djangorestframework: 3.11.0
    djangorestframework-filters 1.1.0.dev0
class Post(models.Model):
  pass

class Comment(models.Model):
  post = models.ForeignKey(Post)


class CommentFilter(FilterSet):
  content = filters.CharFilter(field_name='content', lookup_expr='icontains')

  class Meta:
    model = Comment
    fields = (
      'content',
    )

class PostFilter(FilterSet):
  comment = filters.RelatedFilter(CommentFilter, queryset=Comment.objects.all())

In your viewset just add:

def get_queryset(self):
        return self.queryset.distinct()

And if you're using postgresql you must precede distinct by order-by, using same field, like this:
queryset = YourObject.objects.all().order_by( 'pk').distinct('pk')

Hi @AsheKR. The current workaround as others have stated is to provide an already distinct base queryset to your filterset. However, in the upcoming 1.0.0.dev1 release, RelatedFilter will now obey the distinct argument like other filters.

Fixed by #342.