为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

湖上湖 2021-03-29 13:09:09
我有以下功能,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}]
查看完整描述

3 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

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)


查看完整回答
反对 回复 2021-04-02
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

我认为您正在寻找这个:

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

其中“ response_dict”将是您的字典。


查看完整回答
反对 回复 2021-04-02
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

django.forms.models包中有一个用于该功能的模型:model_to_dict


from django.forms.models import model_to_dict


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


查看完整回答
反对 回复 2021-04-02
  • 3 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信