How to make sure the request will be sorted by valid field - django

This is part of the template tag code, where qs is a collection of queries.

def foo(qs):
    ...
    context['key'] = qs.order_by('an_invalid_field_coming_from_user')

How can I check if a request will be specified by a valid field before the execution of the code goes beyond the scope of the template tag, except that it causes an evaluation?

The as is code does not cause an error because the request is not evaluated. qs.exists()is not an answer, as it will execute the request without ordering.

EDIT . Note that a query can be more complex than a simple simple example Foo.objects.all(), for example, it may contain a method extra()that results in a join.

+3
source share
4 answers

, str (qs.query). , db.

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

, ( ), :

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

order_by() , , django.core.exceptions.FieldError. .

+1

, , . , , Django, . , , , , :

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

Source: https://habr.com/ru/post/1735510/


All Articles