I'm trying to get the field object from a filter like string in Django.
For example,
Sale.objects.filter(product__category__name='shoes')
Given model Sale and the string "product__category__name", is it possible to get the field object for Category.name? (or to be more specific, the verbose_name of that field).
UPDATE
This is what i eventually came up with
from django.db.models.fields import FieldDoesNotExist
def find_field(model, lookup):
lookups = list(reversed(lookup.split("__")))
field = None
while model and lookups:
current = lookups.pop()
field = model._meta.get_field(current)
model = field.related_model
if lookups and model is None:
raise FieldDoesNotExist(lookup)
return field