Set contenttype by name in generic relation in django rest framework

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

Now I can send data to a view that looks like this:

{
    bar: 'content',
    content_type: 1
    object_id: 5
}

The only thing that bothers me is what the interface should know about idtytytyty

Instead, I want you to be able to publish the name content_types, such as "User", as content_type and have the base code for identifying the identifier.

+4
source share
2 answers

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)

    # 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()
    # ...

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('.')
        # ...
+7

DRF , from_native field_to_native - to_internal_value to_representation.

:

class ContentTypeField(serializers.Field):

    def to_representation(self, obj):
        return obj.model

    def to_internal_value(self, data):
        return ContentType.objects.get(model=data)
+1

All Articles