开发者

Parsing Django Queryset JSON

开发者 https://www.devze.com 2023-04-08 12:13 出处:网络
I want to parse a query set to output json data. However I need to make it so that the new jquery ui autocomplete can use it too, and the autocomplete needs the keys label, id and value to be able to

I want to parse a query set to output json data. However I need to make it so that the new jquery ui autocomplete can use it too, and the autocomplete needs the keys label, id and value to be able to read it.

Currently I use:

    emp_list = Employees.objects.filter(eng_name__icontains=q_term)

    json_serializer = serializers.get_serializer('json')()
    json_data = json_serializer.serialize
           (emp_list, ensure_ascii=False, fields=('eng_name', 'chi_name'))

and the output is something like

[{"pk": 1, "model": "system.employees", 
"fields": {"rank": "manager", "eng_name": "Eli"}}, 
........]

I want to be able to parse it into something like this instead:

[{"id": 1, "label": "Eli (manager)", "value": "Eli 开发者_StackOverflow中文版(manager)"}, ....]

what is the best way to do this?


build it in your view then json dump it

employees_output_list = []
for emp in emp_list:
  name_rank_str = "%s (%s)" % (emp.first_name, emp.rank)
  emp_dict = {
    "id": emp.pk,
    "label": name_rank_str,
    "value": name_rank_str,
  }
  employees_output_list.append(emp_dict)
return HttpResponse(json.dumps(employees_output_list))

something like this, don't know your actual field names

0

精彩评论

暂无评论...
验证码 换一张
取 消