I am into a PHP to Django migration project, where I cannot change the schema of my Database
There are places where multiple joins are there for fields without FK and I have no rights to add them now. Even on my Django models because of the huge size of the DB and time constraint on the project delivery.
I am using Django-rest-framework and overriding the list method and queryset to accept these raw sqls.
sql = """SELECT
a.field1,
b.field2
FROM a
LEFT JOIN b ON a.fieldx = b.fieldy"""
The problem is I cannot add the fields of the joined table on my serializer class inside the field tuple because I say model = models.A and this model does not have info about model B.
Your help would be appreciated.
Thank you!
UPDATE I only use viewset. I am not using any view(is this wrong?) My Viewset
class AdminclassinfoViewSet(viewsets.ModelViewSet):
queryset = models.Classroominfo.objects.all()
serializer_class = ClassroominfoSerializer
def list(self, request):
sql = """
SELECT -- DISTINCT
cri.classroomid,
cri.assessmentid,
cri.resourceid,
al.assessmenttype,
al.assessmenttitle,
ri.resourcetype,
ri.resourcetitle,
wwi.writtenworktitle,
cri.writtenworkid,
si.firstname,
si.imageurl,
date(cri.posteddate) as posteddate,
cri.studentid
FROM classroominfo cri
LEFT OUTER JOIN assignassessmentinfo aai ON aai.assessmentid = cri.assessmentid
AND aai.studentid = cri.studentid
LEFT OUTER JOIN assessmentlist al ON al.assessmentid = cri.assessmentid
LEFT OUTER JOIN assignresourceinfo ari ON ari.resourceid = cri.resourceid
AND ari.studentid = cri.studentid
LEFT OUTER JOIN resourceinfo ri ON ri.resourceid = cri.resourceid
LEFT OUTER JOIN assignwrittenworkinfo awwi ON awwi.writtenworkid = cri.writtenworkid
LEFT OUTER JOIN writtenworkinfo wwi ON wwi.writtenworkid = cri.writtenworkid
LEFT OUTER JOIN logininfo li ON li.loginid = cri.studentid
LEFT OUTER JOIN studentinfo si ON si.username = li.username
WHERE ( ari.isclassroom =1 OR
aai.isclassroom =1 OR
awwi.isclassroom=1 )
ORDER BY cri.classroomid DESC
"""
queryset = models.Classroominfo.objects.raw(sql)
serializer_class = ClassroominfoSerializer
serializer = ClassroominfoSerializer(queryset, many=True)
return Response(serializer.data)
My Serializer. I dont know how to refer the joined fields here...
class ClassroominfoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Classroominfo
fields = ('classroomid', 'assessmentid','resourceid',
'writtenworkid')