在order_by django

时间:2017-05-23 07:34:45

标签: python django django-models django-rest-framework

我正在使用条件表达式示例文档中的Case method,我在SO上找到了一些答案,可以contactsstatus_text订购status,在这个例子中我是使用status_text字段。我在我的api get_queryset做了所有这些,我正在做这样的事情,

def get_queryset(self):
    queryset = LeadContact.objects.none()
    user = self.request.user
    # I have some other conditions here

    # This is the conditional expressions that I'm building for order_by
    case_sql = LeadContact.objects.annotate(
        custom_order=Case(
            When(status_text=LeadContactConstants.STATUS_CLIENT, then=Value(1)),
            When(status_text=LeadContactConstants.STATUS_QUALIFIED, then=Value(2)),
            When(status_text=LeadContactConstants.STATUS_CONTACTED, then=Value(3)),
            When(status_text=LeadContactConstants.STATUS_PRISTINE, then=Value(4)),
            output_field=CharField(),
        )
    ).order_by('custom_order')

    return queryset.extra(select={'status_text': case_sql}, order_by=['status_text'])

现在数据库正在抛出这个Traceback:

Traceback:

    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
      58.         return view_func(*args, **kwargs)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
      87.             return self.dispatch(request, *args, **kwargs)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
      466.             response = self.handle_exception(exc)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
      463.             response = handler(request, *args, **kwargs)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/mixins.py" in list
      42.         page = self.paginate_queryset(queryset)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/generics.py" in paginate_queryset
      172.         return self.paginator.paginate_queryset(queryset, self.request, view=self)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/pagination.py" in paginate_queryset
      303.         return list(queryset[self.offset:self.offset + self.limit])
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/query.py" in __iter__
      162.         self._fetch_all()
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all
      965.             self._result_cache = list(self.iterator())
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/query.py" in iterator
      238.         results = compiler.execute_sql()
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
      840.             cursor.execute(sql, params)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
      79.             return super(CursorDebugWrapper, self).execute(sql, params)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
      64.                 return self.cursor.execute(sql, params)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
      98.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
      64.                 return self.cursor.execute(sql, params)
    File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
      124.             return self.cursor.execute(query, args)
    File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py" in execute
      205.             self.errorhandler(self, exc, value)
    File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py" in defaulterrorhandler
      36.     raise errorclass, errorvalue

    Exception Type: ProgrammingError at /api/sales/lead_contact/
    Exception Value: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[<LeadContact: Liam Higgins>, <LeadContact: Juraj  Polerecky>, <LeadContact: Pau' at line 1")

我正在使用这个条件的模型字段是这两个字段,就像我说我也尝试使用status但错误更不一样:

status = models.CharField(max_length=10, choices=LeadContactConstants.STATUSES, default=LeadContactConstants.STATUS_PRISTINE)
status_text = models.CharField(max_length=20, default='', blank=True)

LeadContactConstants模型是:

class LeadContactConstants(object):
    STATUS_PRISTINE = "PRISTINE"
    STATUS_CONTACTED = "CONTACTED"
    STATUS_QUALIFIED = "QUALIFIED"
    STATUS_CLIENT = "CLIENT"

    STATUSES = ((STATUS_PRISTINE, "Virgin"),
                (STATUS_CONTACTED, "Contacted"),
                (STATUS_QUALIFIED, "Qualified"),
                (STATUS_CLIENT, "Client"))

我不知道如何处理这个,所以有人可以解释我发生了什么,我该如何解决这个问题,所以我可以正确地订购我的联系人,谢谢你。

1 个答案:

答案 0 :(得分:2)

我不明白为什么你将其传递给.extra()。这不是它的工作原理:case_sql是查询集本身,您应该将其返回。