django rest framework - how do you flatten nested data?

前端 未结 5 1222
眼角桃花
眼角桃花 2020-12-12 18:13

I have a \'through\' model governing a many to many relationship and i want to be able to return the \'through\' model and the target model as flat data, as opposed to havin

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 18:50

    combining ekuusela's answer and this example from the DRF documentatation, you can also control which fields (from the nested object) you want to display.
    Your serializer would look like this

    class UserDetailsSerializer(serializers.ModelSerializer):
        """User model with Profile. Handled as a single object, profile is flattened."""
    
        profile = ProfileSerializer()
    
        def __init__(self, *args, **kwargs):
            self.allow_fields = kwargs.pop('fields', None)
            super(ProfileSerializer, self).__init__(*args, **kwargs)
    
        class Meta:
            model = User
            fields = ('username', 'email', 'profile')
    
        def to_representation(self, instance):
            representation = super().to_representation(instance)
            profile_representation = representation.pop('profile')
            representation.update(profile_representation)
    
            if self.allow_fields is not None:
                # Drop any fields that are not specified in the `fields` argument.
                allowed = set(self.allow_fields)
                existing = set(representation)
                for field_name in existing - allowed:
                    representation.pop(field_name)
            return representation
    

    And you would instantiate your Serializer as if it was only a singe Model

    serializer = UserDetailsSerializer(user, fields=('username', 'email','profile_field1', 'profile_field2'))
    

提交回复
热议问题