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
- [Django]-Django: return several views from a single URL without redirection
- [Django]-Django REST framework nested serializer and POST nested JSON with files
- [Django]-Django 'User' object has no attribute 'user'
- [Django]-Getting error while running django-cms demo page
- [Django]-How to solve the strptime() caused naive datetime RuntimeWarning?
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.
- [Django]-How to inject same context in many different Django views?
- [Django]-Django: filter queryset when 2 fields have same value
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
- [Django]-Django multiple forms with formsets
- [Django]-Django & South: Adding new field but DatabaseError occurs "table already exists"
- [Django]-Django multiple success urls
Source:stackexchange.com