|
| 1 | +from typing import Optional, Type |
| 2 | + |
| 3 | +from django.db import models |
| 4 | + |
| 5 | +from rest_framework.utils.model_meta import get_field_info |
| 6 | + |
| 7 | + |
| 8 | +def get_target_field(model: Type[models.Model], field: str) -> Optional[models.Field]: |
| 9 | + """ |
| 10 | + Retrieve the end-target that ``field`` points to. |
| 11 | +
|
| 12 | + :param field: A string containing a lookup, potentially spanning relations. E.g.: |
| 13 | + foo__bar__lte. |
| 14 | + :return: A Django model field instance or `None` |
| 15 | + """ |
| 16 | + |
| 17 | + start, *remaining = field.split("__") |
| 18 | + field_info = get_field_info(model) |
| 19 | + |
| 20 | + # simple, non relational field? |
| 21 | + if start in field_info.fields: |
| 22 | + return field_info.fields[start] |
| 23 | + |
| 24 | + # simple relational field? |
| 25 | + if start in field_info.forward_relations: |
| 26 | + relation_info = field_info.forward_relations[start] |
| 27 | + if not remaining: |
| 28 | + return relation_info.model_field |
| 29 | + else: |
| 30 | + return get_target_field(relation_info.related_model, "__".join(remaining)) |
| 31 | + |
| 32 | + # check the reverse relations - note that the model name is used instead of model_name_set |
| 33 | + # in the queries -> we can't just test for containment in field_info.reverse_relations |
| 34 | + for relation_info in field_info.reverse_relations.values(): |
| 35 | + # not sure about this - what if there are more relations with different related names? |
| 36 | + if relation_info.related_model._meta.model_name != start: |
| 37 | + continue |
| 38 | + return get_target_field(relation_info.related_model, "__".join(remaining)) |
| 39 | + |
| 40 | + return None |
0 commit comments