Files
agentic-soc-platform/backend/apps/common/serializers.py
funnywolf b6b4cbf017 0.4.0 I always have a choice
You shape nothing until you hold everything.
2026-06-27 19:08:48 +08:00

21 lines
744 B
Python

from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
class ContentTypeField(serializers.PrimaryKeyRelatedField):
def __init__(self, **kwargs):
super().__init__(queryset=ContentType.objects.all(), **kwargs)
def to_internal_value(self, data):
if isinstance(data, str) and not data.isdigit():
try:
return ContentType.objects.get(model=data)
except ContentType.DoesNotExist as exc:
raise serializers.ValidationError(f"Unknown content type: {data}") from exc
return super().to_internal_value(data)
def to_representation(self, value):
if value is None:
return None
return value.pk