django order_by FieldError exception can not be catched

夙愿已清 提交于 2019-12-23 21:33:38

问题


from django.core.exceptions import FieldError

#This is a method of a class
def _order_item_list(self, item_list, order_items_by, previous_order_by):
    if order_items_by == previous_order_by:
        order_items_by = '-' + order_items_by 

    try:
        result = item_list.order_by(order_items_by)
    except FieldError:
        result = item_list

    return result, order_items_by

Now when I order by valid fields following the generated link,everything works perfect. When I edit a link and add some dummy fieldnames for ordering, it should be catched by this exception and the original list should be returned. But it is not happening, instead I always get a FieldError from django.

FieldError at ...

Cannot resolve keyword u'fgsdffds' into field. Choices are: ...


回答1:


This means there's a typo, or the exception happens elsewhere. Insert a debug line:

 import pdb; pdb.set_trace()

before the try-except and see how the code is executed. Try PUDB or IPDB debuggers instead of the standard one. Many questions disappear when you have a debugger and can see exactly what goes wrong.




回答2:


The reason the exception is not caught is because the QuerySet has not been evaluated yet.

To validate an arbitrary (user-specified) value used for a model field or order_by value, simply check to see if that model has a field by that name.

For example, say you have a model called Ticket and an arbitrary GET parameter called field_name. Here's how you might handle creating a valid QuerySet in views.py:

from django.db.models import FieldDoesNotExist
from myapp.models import Ticket

def index(request):
    default_field = 'id'
    field_name = request.GET.get('field_name', default_field)

    try:
        Ticket._meta.get_field_by_name(field_name)
    except FieldDoesNotExist:
        field_name = default_field

    tickets = Ticket.objects.all().order_by(field_name)
    return ...



回答3:


I faced the same problem and surely it was because the exception is later. In order to raise exception in try-catch block I modified the code in following manner:

try: result = item_list.order_by(order_items_by) result = list(result) except FieldError: result = item_list

This worked for me.



来源:https://stackoverflow.com/questions/7173856/django-order-by-fielderror-exception-can-not-be-catched

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!