mirror of
https://github.com/netbox-community/netbox.git
synced 2024-05-10 07:54:54 +00:00
* Closes #13794: Dynamically populate related objects list under tenant view * get_related_models() should sort models alphabetically by default * Reference Meta.related_objects instead of calling get_fields()
This commit is contained in:
@@ -8,7 +8,7 @@ from itertools import count, groupby
|
||||
import bleach
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.core import serializers
|
||||
from django.db.models import Count, OuterRef, Subquery
|
||||
from django.db.models import Count, ManyToOneRel, OuterRef, Subquery
|
||||
from django.db.models.functions import Coalesce
|
||||
from django.http import QueryDict
|
||||
from django.utils import timezone
|
||||
@@ -567,3 +567,20 @@ def local_now():
|
||||
Return the current date & time in the system timezone.
|
||||
"""
|
||||
return localtime(timezone.now())
|
||||
|
||||
|
||||
def get_related_models(model, ordered=True):
|
||||
"""
|
||||
Return a list of all models which have a ForeignKey to the given model and the name of the field. For example,
|
||||
`get_related_models(Tenant)` will return all models which have a ForeignKey relationship to Tenant.
|
||||
"""
|
||||
related_models = [
|
||||
(field.related_model, field.remote_field.name)
|
||||
for field in model._meta.related_objects
|
||||
if type(field) is ManyToOneRel
|
||||
]
|
||||
|
||||
if ordered:
|
||||
return sorted(related_models, key=lambda x: x[0]._meta.verbose_name)
|
||||
|
||||
return related_models
|
||||
|
||||
Reference in New Issue
Block a user