Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnjaneyuluBatta505/b9e8768c2b924ccd64c2b00f6b090fc7 to your computer and use it in GitHub Desktop.
Save AnjaneyuluBatta505/b9e8768c2b924ccd64c2b00f6b090fc7 to your computer and use it in GitHub Desktop.
django: check if given lookup string is valid for given model
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