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:
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:
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.