我有以下功能,
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),
}
基本上我正在检查用户的facebook朋友在我的django应用程序中的哪一个。如果是,则返回followState。如果用户已在我的Django应用程序上关注它们,则followState基本上返回1或0. 1如果他们没有在我的Django应用程序上关注他们的facebook朋友,则返回0。
我想将一个json类型的字典返回给那个看起来像这样的用户:
[{fbid:222222222222, followState: 0}, {fbid:111111111111, followState: 1}, {fbid:435433434534, followState:1}]
我有字典结构,但我只想像上面的结构一样返回它。
答案 0 :(得分:1)
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.
答案 1 :(得分:1)
我认为你正在寻找这个:
return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json')
其中'response_dict'将是你的字典。
答案 2 :(得分:1)
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)