philipn / django-rest-framework-filters

Better filtering for Django REST Framework
Other
847 stars 131 forks source link

How to distinct result? #331

Closed AsheKR closed 4 years ago

AsheKR commented 4 years ago

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

image

how can i distinct this result?

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())
eliezerp3 commented 4 years ago

In your viewset just add:

def get_queryset(self):
        return self.queryset.distinct()
managingwholes commented 4 years ago

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')

rpkilby commented 4 years ago

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.