Created
November 8, 2018 07:08
-
-
Save AnjaneyuluBatta505/b9e8768c2b924ccd64c2b00f6b090fc7 to your computer and use it in GitHub Desktop.
django: check if given lookup string is valid for given model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models.constants import LOOKUP_SEP | |
from django.core.exceptions import FieldDoesNotExist | |
# django: check if given lookup string is valid for given model | |
def is_valid_lookup_field(model, lookup): | |
# will return first non relational field's verbose_name in lookup | |
for part in lookup.split(LOOKUP_SEP): | |
print(part) | |
try: | |
f = model._meta.get_field(part) | |
except FieldDoesNotExist: | |
# check if field is related | |
for f in model._meta.related_objects: | |
if f.get_accessor_name() == part: | |
break | |
else: | |
return False | |
if f.is_relation: | |
model = f.related_model | |
continue | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment