Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get model field from string path in Django

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
like image 665
haki Avatar asked Dec 05 '25 18:12

haki


1 Answers

To get a verbose_name you should call object._meta.get_field('field').verbose_name

category._meta.get_field('name').verbose_name
like image 144
atn Avatar answered Dec 09 '25 03:12

atn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!