[Answered ]-Django REST framework remove nested json

1👍

Write custom to_representation function in your serializer like this

class IGStatSerializer(serializers.ModelSerializer):
    class Meta:
        model = IGStat
        fields = [
            "account",
            "rank",
            "followers",
            "created",
        ]


class IGSerializer(serializers.ModelSerializer):
    stats = serializers.SerializerMethodField()

    class Meta:
        model = IGAccount
        fields = [
            "id",
            "username",
            "avatar",
            "brand",
            "stats",]
    def get_stats(self, instance):
        today = datetime.today() - timedelta(days=1)
        stat = instance.stats.all().filter(created__year=today.year,
                                           created__month=today.month,
                                           created__day=today.day)
        return IGStatSerializer(stat, allow_null=True, many=True).data

    def to_representation(self, instance):
        data = super().to_representation(instance)
        stats = data.pop('stats', None)
        # If you are sure that there will be only one stats object
        for key, value in stats[0].items():
            data['stats_{key}'.format(key=key)] = value
        return data
    

Leave a comment