Skip to content

Commit dc1df25

Browse files
committed
Use a ContentTypeField in CustomObjectTypeFieldSerializer rather than requiring app_label and model
1 parent 436322d commit dc1df25

File tree

1 file changed

+6
-32
lines changed

1 file changed

+6
-32
lines changed

netbox_custom_objects/api/serializers.py

Lines changed: 6 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from core.models import ObjectType
55
from django.contrib.contenttypes.models import ContentType
66
from extras.choices import CustomFieldTypeChoices
7+
from netbox.api.fields import ContentTypeField
78
from netbox.api.serializers import NetBoxModelSerializer
89
from rest_framework import serializers
910
from rest_framework.exceptions import ValidationError
@@ -37,8 +38,11 @@ class CustomObjectTypeFieldSerializer(NetBoxModelSerializer):
3738
url = serializers.HyperlinkedIdentityField(
3839
view_name="plugins-api:netbox_custom_objects-api:customobjecttypefield-detail"
3940
)
40-
app_label = serializers.CharField(required=False)
41-
model = serializers.CharField(required=False)
41+
related_object_type = ContentTypeField(
42+
queryset=ObjectType.objects.all(),
43+
required=False,
44+
allow_null=True
45+
)
4246

4347
class Meta:
4448
model = CustomObjectTypeField
@@ -56,8 +60,6 @@ class Meta:
5660
"validation_minimum",
5761
"validation_maximum",
5862
"related_object_type",
59-
"app_label",
60-
"model",
6163
"group_name",
6264
"search_weight",
6365
"filter_logic",
@@ -69,20 +71,6 @@ class Meta:
6971
)
7072

7173
def validate(self, attrs):
72-
app_label = attrs.pop("app_label", None)
73-
model = attrs.pop("model", None)
74-
if attrs["type"] in [
75-
CustomFieldTypeChoices.TYPE_OBJECT,
76-
CustomFieldTypeChoices.TYPE_MULTIOBJECT,
77-
]:
78-
try:
79-
attrs["related_object_type"] = ObjectType.objects.get(
80-
app_label=app_label, model=model
81-
)
82-
except ObjectType.DoesNotExist:
83-
raise ValidationError(
84-
"Must provide valid app_label and model for object field type."
85-
)
8674
if attrs["type"] in [
8775
CustomFieldTypeChoices.TYPE_SELECT,
8876
CustomFieldTypeChoices.TYPE_MULTISELECT,
@@ -93,20 +81,6 @@ def validate(self, attrs):
9381
)
9482
return super().validate(attrs)
9583

96-
def create(self, validated_data):
97-
"""
98-
Record the user who created the Custom Object as its owner.
99-
"""
100-
return super().create(validated_data)
101-
102-
def get_related_object_type(self, obj):
103-
if obj.related_object_type:
104-
return dict(
105-
id=obj.related_object_type.id,
106-
app_label=obj.related_object_type.app_label,
107-
model=obj.related_object_type.model,
108-
)
109-
11084

11185
class CustomObjectTypeSerializer(NetBoxModelSerializer):
11286
url = serializers.HyperlinkedIdentityField(

0 commit comments

Comments
 (0)