使用分页和原始查询集的 Django 错误

Ali*_*ani 3 python django pagination django-models

当我尝试将分页添加到我的页面时,它给了我错误object of type 'RawQuerySet' has no len() 视图:

class StudentmessageListView(ListView, LoginRequiredMixin):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'
    template_name = 'student_messagesall.html'
    context_object_name = 'messages_all'
    model = Message
    paginate_by = 3

    def get_queryset(self):
        return Message.objects.raw('SELECT * FROM ertaapp_message where to_prof_id=%s ORDER BY create_date DESC',[self.request.user.id])

    def get_context_data(self, **kwargs):
        context = super(StudentmessageListView, self).get_context_data(**kwargs)
        context['reps'] = ReplyMessage.objects.raw('SELECT * FROM ertaapp_replymessage')
        return context
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

小智 5

您应该返回列表而不是原始查询集。

def get_queryset(self):
    return list(Message.objects.raw('SELECT * FROM ertaapp_message where to_prof_id=%s ORDER BY create_date DESC',[self.request.user.id]))
Run Code Online (Sandbox Code Playgroud)