You can configure WritableFieldthe contenttype identifier to be displayed in a string 'app_label.model':
class ContentTypeField(serializers.WritableField):
def field_from_native(self, data, files, field_name, into):
into[field_name] = self.from_native(data[field_name])
def from_native(self, data):
app_label, model = data.split('.')
return ContentType.objects.get(app_label=app_label, model=model)
def field_to_native(self, obj, field_name):
if self.write_only:
return None
if obj is None:
return self.empty
ct = getattr(obj, field_name)
return '.'.join(ct.natural_key())
class FooSerializer(serializers.ModelSerializer):
content_type = ContentTypeField()
You might want to do a second mapping to limit the choice of content and avoid revealing the names of your applications / models:
CONTENT_TYPES = {
'exposed-contenttype': 'app_label.model'
}
class ContentTypeField(...):
def from_native(self, data):
if data not in CONTENT_TYPES:
raise serializers.ValidationError(...)
app_label, model = CONTENT_TYPES[data].split('.')