此类已查询数据库:
class arizakestirimi_func(ListAPIView):
serializer_class = arizakestirimiserializer
def get_queryset(self):
queryset = isyeriarizabilgileri.objects.raw("""
SELECT
M.id as id,M.isyeri as isyeri,
DATE_PART('day',(M.tarih)::timestamp - (D.mindate)::timestamp) * 24 +
DATE_PART('hour',(M.tarih)::timestamp - (D.mindate)::timestamp) +
DATE_PART('minute',(M.tarih)::timestamp - (D.mindate)::timestamp) / 60 as zamanfarki
FROM arizakestirimi_isyeriarizabilgileri M
INNER JOIN
(SELECT DISTINCT ON (isyeri) isyeri,id as id,durustahmini,tarih as mindate
FROM arizakestirimi_isyeriarizabilgileri
WHERE durustahmini='MEKANIK ARIZA' AND isyeri='15400001'
ORDER BY isyeri, tarih ASC) D
ON M.isyeri = D.isyeri AND M.durustahmini = D.durustahmini
ORDER BY M.tarih ASC
""")
return queryset
这是序列化程序类,我已经在serializer.py中定义了它:
class arizakestirimiserializer(serializers.Serializer):
isyeri = serializers.CharField(max_length=30)
zamanfarki= serializers.FloatField()
当我使用Django rest框架时,我得到了这个json:
[
{
"isyeri": "15400001",
"zamanfarki": 0.0
},
{
"isyeri": "15400001",
"zamanfarki": 7.0
},
{
"isyeri": "15400001",
"zamanfarki": 603.0
},
{
"isyeri": "15400001",
"zamanfarki": 607.0
},
{
"isyeri": "15400001",
"zamanfarki": 1655.0
},
{
"isyeri": "15400001",
"zamanfarki": 1661.0
}
]
我想直接在“ get_queryset”方法中使用此json。如何使用给定的字段名称(例如“ serializers.py”)将queryset结果转换为json。 谢谢
答案 0 :(得分:0)
要在get_queryset方法中获取JSON,您可以这样编辑代码:
class arizakestirimi_func(ListAPIView):
serializer_class = arizakestirimiserializer
def get_queryset(self):
queryset = isyeriarizabilgileri.objects.raw("""
YOUR QUERY
""")
data = self.serializer_class(queryset, many=True).data # This will give you the JSON data
return queryset