Coverage for utilities/relations.py: 33%
7 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 18:35 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 18:35 +0000
1from django.db.models import ManyToOneRel
3__all__ = (
4 'get_related_models',
5)
8def get_related_models(model, ordered=True, include_hidden=False):
9 """
10 Return a list of all models which have a ForeignKey to the given model and the name of the field. For example,
11 `get_related_models(Tenant)` will return all models which have a ForeignKey relationship to Tenant. Set
12 `include_hidden` to also return relationships declared with `related_name='+'`, excluding the
13 automatically created models behind many-to-many fields.
14 """
15 related_models = [
16 (field.related_model, field.remote_field.name)
17 for field in model._meta.get_fields(include_hidden=include_hidden)
18 if type(field) is ManyToOneRel
19 and not field.related_model._meta.auto_created
20 and not getattr(field.related_model, '_netbox_private', False)
21 ]
23 if ordered:
24 return sorted(related_models, key=lambda x: x[0]._meta.verbose_name.lower())
26 return related_models