[Django]-How to make certain that the queryset will be ordered by a valid field – django

3👍

You can force a queryset to validate by running str(qs.query). At that point you can catch the exception without causing it to query the db.

try:
    str(qs.order_by('some_field').query)
except FieldError:
    # bad order_by
    pass

2👍

If you’re really against catching an exception (which you shouldn’t be), you can do this:

if context['key'] in [field.name for field in Foo._meta.fields]:
    qs = Foo.objects.all().order_by(context['key'])
👤Zach

1👍

Using order_by() with a field that doesn’t exist will throw a django.core.exceptions.FieldError. Simply catch that and report the error to the user.

1👍

I am not sure that’s a good idea as there might be security considerations here. I think this will work but I don’t have a copy of Django around to test for sure that the moment. I am pretty sure there is an exception thrown when you do that but if you don’t want to catch that or check preemptively this should work:

if hasattr(Foo, "fieldname") and isinstance(getattr(Foo, "fieldname"), models.Field):
    print "Safe field"
else:
    print "Invalid field"
👤hbar

Leave a comment