【问题标题】:django error using pagination and raw queryset使用分页和原始查询集的 django 错误
【发布时间】:2018-07-15 15:20:39
【问题描述】:

当我尝试向我的页面添加分页时,它给了我错误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

我该如何解决这个问题?

【问题讨论】:

  • 你在这里使用raw有什么原因吗?
  • 我在所有视图中都使用了原始查询集,因为我更熟悉 sql。现在有太多原始查询集我必须更改才能过滤
  • 大多数内置视图都是为使用普通查询集而设计的,因为这些查询看起来很简单,不使用它们会是一个错误。

标签: python django django-models pagination


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 2020-03-21
    • 2021-05-02
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2012-04-30
    • 2019-09-10
    相关资源
    最近更新 更多