deffun_raw_sql_query(**kwargs): song = kwargs.get('song') if song: result = Music.objects.raw( 'SELECT * FROM musics_music WHERE song = %s', [song]) else: result = Music.objects.raw('SELECT * FROM musics_music') return result
views.py:
from rest_framework import status, viewsets from rest_framework.decorators import list_route from rest_framework.response import Response
from musics.models import Music, fun_raw_sql_query from musics.serializers import MusicSerializer
deffun_raw_sql_query(**kwargs): song = kwargs.get('song') if song: result = Music.objects.raw( 'SELECT * FROM musics_music WHERE song = %s', [song]) else: result = Music.objects.raw('SELECT * FROM musics_music') return result
defnamedtuplefetchall(cursor): # Return all rows from a cursor as a namedtuple desc = cursor.description nt_result = namedtuple('Result', [col[0] for col in desc]) return [nt_result(*row) for row in cursor.fetchall()]
deffun_sql_cursor_update(**kwargs): song = kwargs.get('song') pk = kwargs.get('pk')
''' Note that if you want to include literal percent signs in the query, you have to double them in the case you are passing parameters: ''' with connection.cursor() as cursor: cursor.execute( "UPDATE musics_music SET song = %s WHERE id = %s", [song, pk]) cursor.execute("SELECT * FROM musics_music WHERE id = %s", [pk]) # result = cursor.fetchone() result = namedtuplefetchall(cursor) result = [ { 'id': r.id, 'song': r.song, 'singer': r.singer, 'last_modify_date': r.last_modify_date, 'created': r.created, } for r in result ]
return result
views.py:
# /api/music/{pk}/sql_cursor_update/ @detail_route(methods=['put']) defsql_cursor_update(self, request, pk=None): song = request.data.get('song', None) if song: music = fun_sql_cursor_update(song=song, pk=pk) return Response(music, status=status.HTTP_200_OK)