如何获取字典并发送JSON响应

我有以下功能,


def facebooktest(request):

    fb_value = ast.literal_eval(request.body)

    fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())

    for fb_foodie in fb_foodies:

        state = request.user.relationships.following().filter(username = fb_foodie.user.username).exists()

        userData = {

            'fbid': fb_foodie.facebook_id,

            'followState': int(state),

                }

基本上我正在检查我的django应用程序上有哪些用户的Facebook朋友。如果是,则返回followState。followState基本上返回1或0。如果用户已经在我的Django应用程序上关注他们,则返回1;如果用户在我的Django应用程序上未关注其Facebook朋友,则返回0。


我想将json类型字典返回给该用户,如下所示:


[{fbid:222222222222, followState: 0}, {fbid:111111111111, followState: 1}, {fbid:435433434534, followState:1}]



湖上湖
浏览 171回答 3
3回答

LEATH

def facebooktest(request):    fb_value = ast.literal_eval(request.body)    fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())    response = []    for fb_foodie in fb_foodies:        state = request.user.relationships.following().filter(username = fb_foodie.user.username).exists()        userData = {            'fbid': fb_foodie.facebook_id,            'followState': int(state),                }        response.append(userData)    return json.dumps(response)

胡子哥哥

我认为您正在寻找这个:return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')其中“ response_dict”将是您的字典。

杨__羊羊

django.forms.models包中有一个用于该功能的模型:model_to_dictfrom django.forms.models import model_to_dictmodel_to_dict(your_model, fields=[], exclude=[])从帮助中:model_to_dict(instance, fields=None, exclude=None)    Returns a dict containing the data in ``instance`` suitable for passing as    a Form's ``initial`` keyword argument.    ``fields`` is an optional list of field names. If provided, only the named    fields will be included in the returned dict.    ``exclude`` is an optional list of field names. If provided, the named    fields will be excluded from the returned dict, even if they are listed in    the ``fields`` argument.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python