# Buggy code
def list_quotas(request):
    from modoboa.lib.dbutils import db_type

    sort_order, sort_dir = get_sort_order(request.GET, "address")
    mboxes = Mailbox.objects.get_for_admin(
        request.user, request.GET.get("searchquery", None)
    )
    mboxes = mboxes.exclude(quota=0)
    if sort_order in ["address", "quota", "quota_value__bytes"]:
        mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order))
    elif sort_order == "quota_usage":
        where = "admin_mailbox.address||'@'||admin_domain.name"
        db_type = db_type()
        if db_type == "postgres":
            select = "(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100"
        else:
            select = "admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100"
            if db_type == "mysql":
                where = "CONCAT(admin_mailbox.address,'@',admin_domain.name)"
        mboxes = mboxes.extra(
            select={"quota_usage": select},
            where=["admin_quota.username=%s" % where],
            tables=["admin_quota", "admin_domain"],
            order_by=["%s%s" % (sort_dir, sort_order)],
        )
    else:
        raise BadRequest(_("Invalid request"))
    page = get_listing_page(mboxes, request.GET.get("page", 1))
    context = {"headers": _render_to_string(request, "admin/quota_headers.html", {})}
    if page is None:
        context["length"] = 0
    else:
        context["rows"] = _render_to_string(
            request, "admin/quotas.html", {"mboxes": page}
        )
        context["pages"] = [page.number]
    return render_to_json_response(context)


# Traceback (FieldError)
Traceback (most recent call last):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/admin/views/identity.py", line 107, in list_quotas
"mboxes": page

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/lib/webutils.py", line 25, in _render_to_string
context_instance=template.RequestContext(request))

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/loader.py", line 169, in render_to_string
return t.render(context_instance)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py", line 140, in render
return self._render(context)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py", line 134, in _render
return self.nodelist.render(context)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py", line 840, in render
bit = self.render_node(node, context)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py", line 854, in render_node
return node.render(context)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/defaulttags.py", line 156, in render
len_values = len(values)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/paginator.py", line 117, in __len__
return len(self.object_list)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 77, in __len__
self._fetch_all()

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 776, in execute_sql
sql, params = self.as_sql()

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 84, in as_sql
ordering, o_params, ordering_group_by = self.get_ordering()

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 403, in get_ordering
self.query.get_meta(), default_order=asc):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 437, in find_ordering_name
field, cols, alias, joins, opts = self._setup_joins(pieces, opts, alias)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 470, in _setup_joins
pieces, opts, alias)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/query.py", line 1363, in setup_joins
names, opts, allow_many, allow_explicit_fk)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/query.py", line 1283, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))

FieldError: Cannot resolve keyword u'quota_value' into field. Choices are: accessrule, address, alias, armessage, dates, domain, id, mailboxoperation, migration, quota, use_domain_quota, user, usercalendar

# Fixed code
def list_quotas(request):
    from modoboa.lib.dbutils import db_type

    sort_order, sort_dir = get_sort_order(request.GET, "address")
    mboxes = Mailbox.objects.get_for_admin(
        request.user, request.GET.get("searchquery", None)
    )
    mboxes = mboxes.exclude(quota=0)
    if sort_order in ["address", "quota"]:
        mboxes = mboxes.order_by("%s%s" % (sort_dir, sort_order))
    elif sort_order == "quota_value__bytes":
        where = "admin_mailbox.address||'@'||admin_domain.name"
        mboxes = mboxes.extra(
            select={"quota_value__bytes": "admin_quota.bytes"},
            where=["admin_quota.username=%s" % where],
            tables=["admin_quota", "admin_domain"],
            order_by=["%s%s" % (sort_dir, sort_order)],
        )
    elif sort_order == "quota_usage":
        where = "admin_mailbox.address||'@'||admin_domain.name"
        db_type = db_type()
        if db_type == "postgres":
            select = "(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100"
        else:
            select = "admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100"
            if db_type == "mysql":
                where = "CONCAT(admin_mailbox.address,'@',admin_domain.name)"
        mboxes = mboxes.extra(
            select={"quota_usage": select},
            where=["admin_quota.username=%s" % where],
            tables=["admin_quota", "admin_domain"],
            order_by=["%s%s" % (sort_dir, sort_order)],
        )
    else:
        raise BadRequest(_("Invalid request"))
    page = get_listing_page(mboxes, request.GET.get("page", 1))
    context = {"headers": _render_to_string(request, "admin/quota_headers.html", {})}
    if page is None:
        context["length"] = 0
    else:
        context["rows"] = _render_to_string(
            request, "admin/quotas.html", {"mboxes": page}
        )
        context["pages"] = [page.number]
    return render_to_json_response(context)