[Answered ]-Given a QS field lookup key, how to find fields type across joins?

2👍

The info you want is in the class’s meta attribute:

Profile._meta.get_field_by_name('field_name')

This returns:

(field_object, model, direct, m2m)

The model is filled in if you got this from a model object, rather than directly from the class object, direct is true if the field exists on the model (rather than generated as a result of the ORM’s lookup), and m2m is, well, if this field is part of a many-to-many relationship.

[EDIT For ‘__’ relationships]

In the Django source code (db/models/sql/query.py), they disassemble the field type with the following code. I can’t speak to it, but it looks semantically correct:

parts = field_name.split('__')
cur_model = model
for name in parts:
    (field, _, _, _) = cur_model._meta.get_field_by_name(name)
    cur_model = field.rel.to

This basically says that for foreign key relationships the field only contains the ID, and the rel.to is what Django uses to actually get the model that the field refers to, and this loop descends through the list of fields until it finds the last one in your string.

Leave a comment