Django Rest Framework - Read nested data, write integer

前端 未结 4 852
轻奢々
轻奢々 2021-01-01 14:39

So far I\'m extremely happy with Django Rest Framework, which is why I alsmost can\'t believe there\'s such a large omission in the codebase. Hopefully someone knows of a wa

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 15:09

    I create a Field type that tries to solve the problem of the Data Save requests with its ForeignKey in Integer, and the requests to read data with nested data

    This is the class:

    class NestedRelatedField(serializers.PrimaryKeyRelatedField):
    """
        Model identical to PrimaryKeyRelatedField but its
        representation will be nested and its input will
        be a primary key.
    """
    
    def __init__(self, **kwargs):
        self.pk_field = kwargs.pop('pk_field', None)
        self.model = kwargs.pop('model', None)
        self.serializer_class = kwargs.pop('serializer_class', None)
        super().__init__(**kwargs)
    
    def to_representation(self, data):
        pk = super(NestedRelatedField, self).to_representation(data)
        try:
            return self.serializer_class(self.model.objects.get(pk=pk)).data
        except self.model.DoesNotExist:
            return None
    
    def to_internal_value(self, data):
        return serializers.PrimaryKeyRelatedField.to_internal_value(self, data)
    

    And so it would be used:

    class PostModelSerializer(serializers.ModelSerializer):
    
        message = NestedRelatedField(
             queryset=MessagePrefix.objects.all(),
             model=MessagePrefix,
             serializer_class=MessagePrefixModelSerializer
       )
    

    I hope this helps you.

提交回复
热议问题