Removing fields from json

I have a view function that displays json. I can indicate which columns I want in my json, but I do not know how to change the name of the key fields. Like the pk field, it should be id.

I use this autocomplete control ( http://loopj.com/2009/04/25/jquery-plugin-tokenizing-autocomplete-text-entry/ ) and it requires json to have certain fields.

from django.http import HttpResponse
from django.shortcuts import render_to_response
from iCookItThisWay.recipes import models
from django.core import serializers
from django.utils import simplejson

def index(request, template_name):
    meal_types = []
    q = ''

    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']

    if len(q) > 0:
        meal_types = models.MealType.objects.filter(name__istartswith=q)

    json_serializer = serializers.get_serializer("json")()
    sdata = json_serializer.serialize(meal_types, ensure_ascii=False, fields = ('id', 'name'))

    return HttpResponse(simplejson.dumps(sdata), mimetype='application/json')

Could you also point me to the documentation. I feel like I'm holding on to looking for documentation.

+3
source share
1 answer

Instead of using a serializer, you can build the dict file manually and convert it to json via .dumps ()

meal_types = models.MealType.objects.filter(name__istartswith=q)
results = []
for meal_type in meal_types:
    results.append(
        {'id': meal_type.id,
         'name': meal_type.name})

return HttpResponse(simplejson.dumps(results), mimetype='application/json')

, :

results = [{'id': mt.id, 'name': mt.name} for mt in meal_types]
+1

Source: https://habr.com/ru/post/1750950/


All Articles