Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions netbox_custom_objects/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import sys
import warnings

from django.core.exceptions import AppRegistryNotReady
from django.db import transaction
from django.db.utils import DatabaseError, OperationalError, ProgrammingError
from netbox.plugins import PluginConfig
Expand Down Expand Up @@ -52,16 +51,40 @@ class CustomObjectsPluginConfig(PluginConfig):
required_settings = []
template_extensions = "template_content.template_extensions"

def ready(self):
from .models import CustomObjectType
from netbox_custom_objects.api.serializers import get_serializer_class

# Suppress warnings about database calls during app initialization
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", category=RuntimeWarning, message=".*database.*"
)
warnings.filterwarnings(
"ignore", category=UserWarning, message=".*database.*"
)

# Skip database calls if running during migration or if table doesn't exist
if is_running_migration() or not check_custom_object_type_table_exists():
super().ready()
return

qs = CustomObjectType.objects.all()
for obj in qs:
model = obj.get_model()
get_serializer_class(model)

super().ready()

def get_model(self, model_name, require_ready=True):
self.apps.check_apps_ready()
try:
# if the model is already loaded, return it
return super().get_model(model_name, require_ready)
except LookupError:
try:
self.apps.check_apps_ready()
except AppRegistryNotReady:
raise
pass

model_name = model_name.lower()
# only do database calls if we are sure the app is ready to avoid
# Django warnings
if "table" not in model_name.lower() or "model" not in model_name.lower():
Expand Down
69 changes: 5 additions & 64 deletions netbox_custom_objects/field_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,6 @@ def get_model_field(self, field, **kwargs):
to_model = content_type.model

# Extract our custom parameters and keep only Django field parameters
generating_models = kwargs.pop('_generating_models', getattr(self, '_generating_models', set()))
field_kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
field_kwargs.update({"default": field.default, "unique": field.unique})

Expand Down Expand Up @@ -427,27 +426,7 @@ def get_model_field(self, field, **kwargs):
return f
else:
# For cross-referential fields, use skip_object_fields to avoid infinite loops
# Check if we're in a recursion situation using the parameter or stored attribute
if generating_models and custom_object_type.id in generating_models:
# We're in a circular reference, don't call get_model() to prevent recursion
# Use a string reference instead
model_name = f"{APP_LABEL}.{custom_object_type.get_table_model_name(custom_object_type.id)}"
# Generate a unique related_name to prevent reverse accessor conflicts
table_model_name = field.custom_object_type.get_table_model_name(
field.custom_object_type.id
).lower()
related_name = f"{table_model_name}_{field.name}_set"
f = models.ForeignKey(
model_name,
null=True,
blank=True,
on_delete=models.CASCADE,
related_name=related_name,
**field_kwargs
)
return f
else:
model = custom_object_type.get_model(skip_object_fields=True)
model = custom_object_type.get_model(skip_object_fields=True)
else:
# to_model = content_type.model_class()._meta.object_name
to_ct = f"{content_type.app_label}.{to_model}"
Expand Down Expand Up @@ -479,19 +458,7 @@ def get_form_field(self, field, for_csv_import=False, **kwargs):
)
custom_object_type = CustomObjectType.objects.get(pk=custom_object_type_id)

# Check if we're in a recursion situation
generating_models = getattr(self, '_generating_models', set())
if generating_models and custom_object_type.id in generating_models:
# We're in a circular reference, don't call get_model() to prevent recursion
# Use a minimal approach or return a basic field
return DynamicModelChoiceField(
queryset=custom_object_type.get_model(skip_object_fields=True).objects.all(),
required=field.required,
# Remove initial=field.default to allow Django to handle instance data properly
selector=True,
)
else:
model = custom_object_type.get_model()
model = custom_object_type.get_model()
else:
# This is a regular NetBox model
model = content_type.model_class()
Expand Down Expand Up @@ -801,20 +768,7 @@ def get_form_field(self, field, for_csv_import=False, **kwargs):
)
custom_object_type = CustomObjectType.objects.get(pk=custom_object_type_id)

# For cross-referential fields, use skip_object_fields to avoid infinite loops
# Check if we're in a recursion situation using the parameter or stored attribute
generating_models = getattr(self, '_generating_models', set())
if generating_models and custom_object_type.id in generating_models:
# We're in a circular reference, don't call get_model() to prevent recursion
# Use a minimal approach or return a basic field
return DynamicModelMultipleChoiceField(
queryset=custom_object_type.get_model(skip_object_fields=True).objects.all(),
required=field.required,
# Remove initial=field.default to allow Django to handle instance data properly
selector=True,
)
else:
model = custom_object_type.get_model(skip_object_fields=True)
model = custom_object_type.get_model(skip_object_fields=True)
else:
# This is a regular NetBox model
model = content_type.model_class()
Expand Down Expand Up @@ -905,13 +859,7 @@ def after_model_generation(self, instance, model, field_name):
# Self-referential field - resolve to current model
to_model = model
else:
# Cross-referential field - check for recursion before calling get_model()
generating_models = getattr(self, '_generating_models', set())
if generating_models and custom_object_type.id in generating_models:
# We're in a circular reference, don't call get_model() to prevent recursion
return
else:
to_model = custom_object_type.get_model()
to_model = custom_object_type.get_model()
else:
to_ct = f"{content_type.app_label}.{content_type.model}"
to_model = apps.get_model(to_ct)
Expand Down Expand Up @@ -956,14 +904,7 @@ def create_m2m_table(self, instance, model, field_name):
pk=custom_object_type_id
)

# Check if we're in a recursion situation
generating_models = getattr(self, '_generating_models', set())
if generating_models and custom_object_type.id in generating_models:
# We're in a circular reference, don't call get_model() to prevent recursion
# Use a minimal approach or skip this field
return
else:
to_model = custom_object_type.get_model()
to_model = custom_object_type.get_model()
else:
to_model = content_type.model_class()

Expand Down
Loading