使用python3和django,我如何推入JSON DICT对象

时间:2015-11-01 05:20:36

标签: python json django

我正在使用Django Views发布视图。

def index_view(request):
    enlisted = models.Subscription.objects.rankset("E").active().count()
    officer = models.Subscription.objects.rankset("O").active().count()
    civilian = models.Subscription.objects.rankset("C").active().count()
    lifer = models.Subscription.objects.lifer().active().count()
    subscriptions = models.Subscription.objects.all().order_by("-Modified")
    statembr = models.Member.objects.values('State').annotate(c=Count('State')).exclude(State='')
    statembrmap = dict([(type_and_count['State'], type_and_count['c']) for type_and_count in statembr])
    stateunit = models.Unit.objects.values('State').annotate(c=Count('State')).exclude(State='')
    stateunitmap = dict([(type_and_count['State'], type_and_count['c']) for type_and_count in stateunit])
    ctryunit = models.Unit.objects.values('Country').annotate(c=Count('Country')).exclude(Country='')
    ctryunitmap = dict([(type_and_count['Country'], type_and_count['c']) for type_and_count in ctryunit])
    ctrymbr = models.Member.objects.values('Country').annotate(c=Count('Country')).exclude(Country='')
    ctrymbrmap = dict([(type_and_count['Country'], type_and_count['c']) for type_and_count in ctrymbr])
    units = models.Unit.objects.values('Unit_name', 'Hull_type', 'Hull_number').annotate(c=Count('memberunit__Member'))
    context = {'ctrymbrmap': ctrymbrmap, 'statembrmap': statembrmap, 'enlisted': enlisted, 'officer': officer,
               'civilian': civilian, 'lifer': lifer, 'units': units,
               'Subscriptions': subscriptions, 'statunitmap': stateunitmap, 'ctryunitmap': ctryunitmap}
    return render(request, 'index.html', context)

如果你看到变量context,它就是硬编码的。有没有办法去推送"进入context变量,以允许动态构造所述变量?感谢。

1 个答案:

答案 0 :(得分:2)

我认为你正在寻找这个:

context.update({'key1': 'value1', 'key2': 'value2'})

context['key1'] = 'value 1'