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

时间:2018-02-05 17:27:40

标签: python django django-models pagination

当我尝试在页面中添加分页时,它会给我一个错误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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

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

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