mirror of
				https://github.com/netbox-community/netbox.git
				synced 2024-05-10 07:54:54 +00:00 
			
		
		
		
	Introduce GenericObjectSerializer
This commit is contained in:
		@@ -2,6 +2,7 @@ from rest_framework import serializers
 | 
			
		||||
 | 
			
		||||
from .base import *
 | 
			
		||||
from .features import *
 | 
			
		||||
from .generic import *
 | 
			
		||||
from .nested import *
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										31
									
								
								netbox/netbox/api/serializers/generic.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										31
									
								
								netbox/netbox/api/serializers/generic.py
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,31 @@
 | 
			
		||||
from django.contrib.contenttypes.models import ContentType
 | 
			
		||||
from rest_framework import serializers
 | 
			
		||||
 | 
			
		||||
from netbox.api import ContentTypeField
 | 
			
		||||
from utilities.utils import content_type_identifier
 | 
			
		||||
 | 
			
		||||
__all__ = (
 | 
			
		||||
    'GenericObjectSerializer',
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
class GenericObjectSerializer(serializers.Serializer):
 | 
			
		||||
    """
 | 
			
		||||
    Minimal representation of some generic object identified by ContentType and PK.
 | 
			
		||||
    """
 | 
			
		||||
    object_type = ContentTypeField(
 | 
			
		||||
        queryset=ContentType.objects.all()
 | 
			
		||||
    )
 | 
			
		||||
    object_id = serializers.IntegerField()
 | 
			
		||||
 | 
			
		||||
    def to_internal_value(self, data):
 | 
			
		||||
        data = super().to_internal_value(data)
 | 
			
		||||
        model = data['object_type'].model_class()
 | 
			
		||||
        return model.objects.get(pk=data['object_id'])
 | 
			
		||||
 | 
			
		||||
    def to_representation(self, instance):
 | 
			
		||||
        ct = ContentType.objects.get_for_model(instance)
 | 
			
		||||
        return {
 | 
			
		||||
            'object_type': content_type_identifier(ct),
 | 
			
		||||
            'object_id': instance.pk,
 | 
			
		||||
        }
 | 
			
		||||
		Reference in New Issue
	
	Block a user