[Django]-Django order_by FieldError exception can not be catched

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.

4👍

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 ...
👤Brian

0👍

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.

👤Vijay

Leave a comment