class Foo(models.Model):
bar = models.CharField(max_length=300)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
class FooViewSet(viewsets.ModelViewSet):
model = Foo
serializer_class = FooSerializer
我现在可以将数据发布到如下所示的视图集:
{
bar: 'content',
content_type: 1
object_id: 5
}
唯一让我烦恼的是,前端必须知道内容类型ID
相反,我希望能够发布content_types名称,例如' User' as content_type并让后端确定id。
答案 0 :(得分:8)
您可以自定义WritableField
以将contenttype id映射到'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)
# If content_type is write_only, there is no need to have field_to_native here.
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()
# ...
您可能需要执行第二次映射以限制contenttype的选择并避免推出应用/型号名称:
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('.')
# ...
答案 1 :(得分:3)
DRF 3.x中用于读/写操作的最简单,最干净的方法:
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from .models import Foo
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
content_type = serializers.SlugRelatedField(
queryset=ContentType.objects.all(),
slug_field='model',
)
然后,您可以使用型号名称执行CRUD操作:
data = {
'bar': "content",
'content_type': "model_name",
'object_id': 1,
}
答案 2 :(得分:1)
DRF已经改变,现在有了新的方法 - to_internal_value和to_representation,而不是from_native和field_to_native。
现在更简单了:
class ContentTypeField(serializers.Field):
def to_representation(self, obj):
return obj.model
def to_internal_value(self, data):
return ContentType.objects.get(model=data)