Django No. 16-3 schemes for returning the data to the front-end page as json data type

I. Introduction

Django's ORM framework provides many methods for querying database table data, and different methods return different results. Different methods have their own corresponding usage scenarios.

The number of main commonly used query methods is 13, and the method return value is an iterable object QuerySet method only these 8 methods: all(), filter(), exclude(), order_by(), reverse(), values(), values_list(), distinct();

If the front-end personnel require that the data type of the return value of the interface is json, the back-end personnel must indirectly convert the value of the iterable object QuerySet to the value of the non-iterable object and the non-json data type through other methods and convert the value When it is the value of one of the input parameters when the JsonResponse class is initialized, the object after the initialization of the JsonResponse class is finally provided to the front-end personnel as the final interface return value.

The so-called scheme of converting the return value of the interface to the value of the iterable object QuerySet indirectly into the value of the json data type through other methods, currently there are only three schemes (we only need to remember these three):

⑴. Option 1: Use serializers                                                 

     Main function: Convert the return value of the interface to the value of the iterable object QuerySet to the value of the json data type (that is, the data type in the python language is the data type of the string);

    (This kind of program only needs to be understood, basically not needed)

⑵. Option 2: Use model_to_dict                                           

     Main function: Convert the return value of the interface to the value of the iterable object QuerySet into the value of the data type of dict in the python language;

    (This kind of program only needs to be understood, basically not needed)

⑶. Scheme 3: Use method value combined with method list                         

     Main function: Convert the return value of the interface to the value of the iterable object QuerySet into the value of the data type of the list data type in the python language;

    (This kind of scheme is the simplest, basically will use this, we must focus on knowing how to use it)

detail:

① Question: Why does the data type of the data returned by the view function return value to the front-end page sometimes need to be json?

Probably the answer:

At present, most of the company's R&D team adopts the separation of front and back ends for project development, which can greatly improve the efficiency of project development and maintenance.

Therefore, front-end developers generally require back-end developers to convert the return value of the interface into data of data type json and send it to front-end developers. After the front-end developers get the data of data type json, they will process it separately and obtain it to themselves. The desired field data is used for data loading and rendering of the corresponding html page.

②. Question: How to understand the data type of json?

Probably the answer:

The data type of json is actually a string.

The data type of json can be understood as U.S. dollars, and every country in the world can trade in U.S. dollars.

Any data type provided by python can be understood as RMB, any data type provided by java can be understood as Euro, any data type provided by PHP can be understood as Japanese Yen, and any data type provided by C language can be understood as Hong Kong dollar. , The data type required by html must only be json.

Therefore, regardless of the interface return value written in which back-end language, if the front-end personnel require the data type of the interface return value to be json, the back-end personnel must convert the data type of the interface return value, that is, convert the original data type (such as python The language list data type/dict data type) can be converted to the json data type before it can be regarded as the final interface return value.

 

Two, simple analysis of the source code of the JsonResponse class

detail:

①.json is a commonly used data format at present. Sometimes our back-end developers need to return a json-formatted data to the front-end developers, and the JsonResponse class can meet such needs.

②. Through [from django.http import JsonResponse] and [class JsonResponse(HttpResponse)], we can know that the JsonResponse class is a subclass of HttpResponse and inherits most of the behaviors from the parent class to help create json responses.

1. The source code of the JsonResponse class is as follows

class JsonResponse(HttpResponse):

    """

    An HTTP response class that consumes data to be serialized to JSON.



    :param data: Data to be dumped into json. By default only ``dict`` objects

      are allowed to be passed due to a security flaw before EcmaScript 5. See

      the ``safe`` parameter for more information.

    :param encoder: Should be a json encoder class. Defaults to

      ``django.core.serializers.json.DjangoJSONEncoder``.

    :param safe: Controls if only ``dict`` objects may be serialized. Defaults

      to ``True``.

    :param json_dumps_params: A dictionary of kwargs passed to json.dumps().

    """



    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,

                 json_dumps_params=None, **kwargs):

        if safe and not isinstance(data, dict):

            raise TypeError(

                'In order to allow non-dict objects to be serialized set the '

                'safe parameter to False.'

            )

        if json_dumps_params is None:

            json_dumps_params = {}

        kwargs.setdefault('content_type', 'application/json')

        data = json.dumps(data, cls=encoder, **json_dumps_params)

        super().__init__(content=data, **kwargs)

2. The general meaning and function of each parameter in the constructor of the JsonResponse class

①. Input parameter [data]: A value of data type dict should be passed to it (you can also not pass a value of data type dict to it), and it will be converted into data in json format.   

②. Input parameter [encoder]: The default value is django.core.serializers.json.DjangoJSONEncoder or DjangoJSONEncoder, which is used to serialize data. (For more knowledge about serialization, you can search for json serialization on Baidu to learn. At present, you only need to know how to use it) ③. Entry [safe]: The default value is True. If the value is set to False, it means that any object (such as list/tuple/dict) can be passed for serialization; if the value is set to True and the value of the first parameter data is not a dict object, a TypeError will be thrown. 

④. Input parameters [json_dumps_params]: The default value is None. For the newly added input parameter in django1.9 version, you can pass an object processed by the json.dump() method in the json library in python to the input parameter as the input parameter value to generate a response. (Understand it)

3. [Scheme 1: Using serializers] the specific plan realization process

1. The first step: first write the view function of the relevant code content

Related code:


from django.core import serializers

import json

from django.http import JsonResponse





def search_person(request):

    # 第一种返回给前端页面的是json数据类型的方案:使用【serialize】

    data = {}

    a = Person.objects.all()

    b = serializers.serialize("json", a)

    print(type(b))

    print(b)

    print("================================分割线1===================================")

    c = json.load(b)

    print(type(c))

    print(c)

    print("================================分割线2===================================")

    data["result"] = c

    print(data["result"])

    print(data)

    print("================================分割线3===================================")

    d = JsonResponse(data, json_dumps_params={"ensure_ascii": False})



    print(type(d))

    print(d)

    print(d.content)

    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})

2. Step 2: Visit the website [ http://127.0.0.1:8000/search_person ] in any browser to view the data display on the result page

3. The third step: You can get the interface return value to the website [https://www.json.cn/] for analysis and formatting, which is convenient for visual inspection

4. Step 4 : Check the printed log information to see if it meets the expected result

4. [Scheme 2: Use model_to_dict] the specific plan realization process

1. The first step: first write the view function of the relevant code content


Related code:

From django.forms import model_to_dict



def search_person(request):

    # 第二种返回给前端页面的是json数据类型的数据方案:【方案2:使用方法model_to_dict】

    res = Person.objects.all()

    json_list = []

    for i in res:

        json_dict = model_to_dict(i)

        json_list.append(json_dict)

    print(json_list)

    return JsonResponse(json_list, safe=False, json_dumps_params={"ensure_ascii": False})

2. Step 2: Visit the website [ http://127.0.0.1:8000/search_person ] in any browser to view the data display on the result page

3. Step 3 : Check the printed log information to see if it meets the expected result

5. [Scheme 3: Use method value combined with method list] the specific plan realization process

1. The first step: first write the view function of the relevant code content


Related code:

def search_person(request):

    # 第三种返回给前端页面的是json数据类型的数据方案:【方案3:使用方法value()跟方法list结合】

    res = Person.objects.all().values()

    print(type(res))

    print(res)

    print("================================分割线1===================================")

    res = list(res)

    print(type(res))

    data = {"result": res}

    print(data)

    print("================================分割线2===================================")

    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})

2. Step 2: Visit the website [ http://127.0.0.1:8000/search_person ] in any browser to view the data display on the result page

3. Step 3 : Check the printed log information to see if it meets the expected result

detail:

①. [Scheme 3: Use method value() combined with method list] is the mainstream and commonly used solution, and we can choose this solution 3 as far as possible when we develop the platform.

Guess you like

Origin blog.csdn.net/LYX_WIN/article/details/114405004