Django: Get database object value in template using Ajax

后端 未结 2 1740
耶瑟儿~
耶瑟儿~ 2021-02-02 04:26

I want to fetch database object depending on user selection. I know one possible solution could be Ajax, but I don\'t know how to get about it. Here is the code:

2条回答
  •  孤独总比滥情好
    2021-02-02 04:53

    I will assume that you are using AJAX requests.

    You cannot directly return a query result or model instance as JSON. But you can serialize it. Here is one possibility:

    from django.forms.models import model_to_dict
    model_to_dict(intance, fields=[], exclude=[])
    

    model_to_dict takes 3 parameters:

    1. A specific model instance
    2. fields to include
    3. fields to exclude

    Parameters 2 and 3 are optional. If you do not specify the fields, the method will serialize all of them. To do that for multiple instances (for example a query result), just do that in a loop for each instance.

提交回复
热议问题