django 使用分页和原始查询集时出错

问题描述 投票:0回答:1

当我尝试向页面添加分页时,出现错误

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

我该如何解决这个问题?

python django django-models pagination
1个回答
5
投票

自从 Django 2.1 引入了 RawQuerySet 的 len() 方法以来,问题和答案都不再相关了。


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

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]))
© www.soinside.com 2019 - 2024. All rights reserved.