对Django 的结果集进行序列化


django 对model 模型的操作返回结果为QuerySet,可以用下面的方法序列化返回给前端

>>> from cost_app.models import AllMonthReport
>>> from django.core.serializers import serialize
>>> all_amount = AllMonthReport.objects.all().order_by('-month', 'item')
>>> json_data = serialize('json', all_amount)
>>> print(json_data)
[{"model": "cost_app.allmonthreport", "pk": 20, "fields": {"month": "2020-02", "item": "al", "amount": 3592.56}}, {"model": "cost_app.allmonthreport", "pk": 16, "fields": {"month": "2020-02", "item": "tc", "amount": 13135.010000000006}}, {"model": "cost_app.allmonthreport", "pk": 9, "fields": {"month": "2020-01", "item": "al", "amount": 4028.12}}, {"model": "cost_app.allmonthreport", "pk": 10, "fields": {"month": "2020-01", "item": "tc", "amount": 15233.53999999999}}, {"model": "cost_app.allmonthreport", "pk": 19, "fields": {"month": "2019-12", "item": "al", "amount": 8660.83}}, {"model": "cost_app.allmonthreport", "pk": 8, "fields": {"month": "2019-12", "item": "tc", "amount": 11115.730000000001}}, {"model": "cost_app.allmonthreport", "pk": 18, "fields": {"month": "2019-11", "item": "al", "amount": 8431.63}}, {"model": "cost_app.allmonthreport", "pk": 15, "fields": {"month": "2019-11", "item": "tc", "amount": 2683.2}}]