How to couple Django connection.cursor() with rest_framework generics?

20 Views Asked by At

Working on a project where we want to bypass Django ORM and use direct SQL queries instead. We will have lots of simple APIs, hence wanted to use rest_framework generics view classes. But querysets implemented via connection.cursor() don't update when data changes. I.e. if a POST is made to a generics.ListCreateAPIView, the new data gets saved to the DB, but consecutive GET requests still show the dataset as it was before the POST.

MODELS:

from django.db import models    
class identifier_type(models.Model):
        type_name = models.CharField(max_length=25, unique=True)

SERIALIZERS:

from rest_framework import serializers
from .models import *

class IdentifierTypeSerializer (serializers.ModelSerializer):
    class Meta:
        model = identifier_type
        fields = ['id', 'type_name']

VIEWS:

from rest_framework import generics
from .models import identifier_type
from .serializers import IdentifierTypeSerializer
from .queries import identifier_type_select_all
from .utils import dict_fetch_all

class IdentifierTypesCR(generics.ListCreateAPIView): 
    queryset = dict_fetch_all(identifier_type_select_all) # does not update GET after PUT
    # queryset = identifier_type.objects.all()  # alternative- Django ORM updates GET after PUT
    serializer_class = IdentifierTypeSerializer

UTILS:

from django.db import connection
def dict_fetch_all(query, *args):
    cursor = connection.cursor()
    cursor.execute(query, *args)
    desc = cursor.description
    rows = cursor.fetchall()
    if rows:
        return [dict(zip([col[0] for col in desc], row)) for row in rows]
    else:
        return None

QUERIES:

identifier_type_select_all = "SELECT * FROM staticdata_identifier_type"

URLS:

from django.urls import path
from . import views

urlpatterns = [
    path("api/crud/identifier_types", views.IdentifierTypesCR.as_view(), name="api_identifier_types"),
]
0

There are 0 best solutions below