def change_obj_to_dict(self,temp): dict = {} dict["wxh_name"] = temp.wxh_name dict["types"] = temp.types dict["subject"] = temp.subject dict["ids"] = temp.ids # 虽然产品表里没有替代型号,但是通过sql语句的raw()查询可以查到结果中是包含非实例对象的字段的 dict["rates"] = temp.rates dict["pv"] = temp.pv dict["phone"] = temp.phone dict["manage_status"] = temp.manage_status dict["names"] = temp.names dict["status"] = temp.status return dict
models2=AutoWxh.objects.raw('SELECT auto_wxh.id, wxh_name,auto_wxh.type as types,`subject`,auto_wxh.gzh_id as ids,tab2.total_open_rate as rates,tab2.totallys_pv as pv,phone,manage_status,auto_category.name as names,auto_wxh.status as status FROM auto_wxh LEFT JOIN (SELECT gzh_id,SUM(open_rate) AS total_open_rate,SUM(total_pv) as totallys_pv FROM auto_article_list WHERE refdate="20230223" GROUP BY gzh_id) AS tab2 on auto_wxh.gzh_id = tab2.gzh_id LEFT JOIN auto_category on auto_wxh.category_id=auto_category.id ORDER BY tab2.total_open_rate DESC ') data2 = [] if models2 and len(models2) > 0: for temp in models2: data2.append(self.change_obj_to_dict(temp)) # *****最终获得data2是一个字典的集合 page_obj = Paginator(data2, pagesize) try: page_data = page_obj.page(page) queryset = page_data.object_list has_next = page_data.has_next() except EmptyPage: queryset = [] has_next = False return SuccessResponse({'datas': queryset,'has_next': has_next,'pagenumber':page_obj.count,'pagecount':page_obj.num_pages})
思路一
主要思路就是将object对象转换成字典,再将字典装进列表中,打包进
paginator里面
django使用raw()执行sql语句多表查询_神奇洋葱头的博客-CSDN博客_django raw
思路二
if models1 and len(models1) > 0: for temp in models1: temp.__dict__.pop('_state') data2.append(temp.__dict__)
直接将models直接对象直接转成对象过滤多余不能识别的的键