AssertionError Unable to filter query after slice has been done

I am trying to create a view that restricts results based on user authentication. For some reason, cutting lists always results in an AssertionError. It is not possible to filter the query after the slice has been done.

class CustomGalleryDetailView(DetailView):

    def get_queryset(self):
        if not self.request.user.is_authenticated():
            return Gallery.objects.on_site().is_public()[:3]

        else:
            return Gallery.objects.on_site().is_public()

Even when i try

return Gallery.objects.all()[:3], 

Without further filtering, I still get the same error.

+4
source share
1 answer

You are using a class DetailView.

Here you can see in Django docs forDetailsView that, after calling the method, the get_querysetnext method get_object(located in the class SingleObjectMixin)

: https://github.com/django/django/blob/1.7/django/views/generic/detail.py#L21

, , , .filter(pk=pk)

, -, :

class CustomGalleryDetailView(DetailView):

    def get_queryset(self):
        if not self.request.user.is_authenticated():
            qs = Gallery.objects.on_site().is_public()
            valid_ids = qs.values_list('pk', flat=True)[:3]
            return Gallery.objects.filter(pk__in=valid_ids)

        else:
            return Gallery.objects.on_site().is_public()
+3

Source: https://habr.com/ru/post/1568264/


All Articles