[Answered ]-Filter returns much more objects

1๐Ÿ‘

โœ…

I think get_queryset method has an issue.
You can remove duplicated album objects with distinct method.

This problem occurs because a join occurs while evaluating a query.

As-is

has_photos = self.request.query_params.get('has_photos')
if has_photos == 'true':
    return PhotoAlbum.objects.filter(photos__isnull=False)
elif has_photos == 'false':
    return PhotoAlbum.objects.filter(photos__isnull=True)

To-be (1)

has_photos = self.request.query_params.get('has_photos')
if has_photos == 'true':
    return PhotoAlbum.objects.filter(photos__isnull=False).distinct()
elif has_photos == 'false':
    return PhotoAlbum.objects.filter(photos__isnull=True).distinct()

To-be (2)

qs = PhotoAlbum.objects.annotate(count=Count('photos'))
has_photos = self.request.query_params.get('has_photos')
if has_photos == 'true':
    return qs.filter(count__gte=1)
elif has_photos == 'false':
    return qs.filter(count=0)
๐Ÿ‘คJaewoo Pyo

Leave a comment