0
def participant_specific_donation(self, participant):
    donations = Donation.objects.filter(participant = participant)

    helper = {}

    for donation in donations:
        ##helper['donation_date'] = donation.date
        helper['donation_amount'] = donation.amount
    return helper

def participant_specific(request, participant):
helper = RelayFunctions()
info = helper.participant_specific_donation(participant)
info1 = helper.participant_specific_milestone(participant)

data = [ 'participant_specific_donation' : info , 'participant_specific_milestone' : info1 ]
json_serializer = serializers.get_serializer("json")()
response = json_serializer.serialize(data, ensure_ascii=False)
return HttpResponse(response, mimetype="application/json")

错误:“dict”对象没有属性“_meta”这与我如何调用字典有关吗?我想将两个对象组合成一个。然后解析为json。

这是追溯。

Traceback:
 File "/home/vtrelayc/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
   111.                         response = callback(request, *callback_args, **callback_kwargs)
 File "/home/vtrelayc/projects/relay/relayapp/views.py" in participant_specific
   192.     response = json_serializer.serialize(data, ensure_ascii=False)
 File "/home/vtrelayc/lib/python2.6/site-packages/django/core/serializers/__init__.py" in serialize
  98.     s.serialize(queryset, **options)
File "/home/vtrelayc/lib/python2.6/site-packages/django/core/serializers/base.py" in serialize
  46.             concrete_model = obj._meta.concrete_model

Exception Type: AttributeError at /participants/specific/1/
Exception Value: 'dict' object has no attribute '_meta'

def participant_specific(request, participant):
helper = RelayFunctions()
info = helper.participant_specific_donation(participant)
info1 = helper.participant_specific_milestone(participant)
data = [ 'participant_specific_donation' : info , 'participant_specific_milestone' : info1 ]
json_serializer = serializers.get_serializer("json")()
response = json_serializer.serialize(data, ensure_ascii=False) ...
return HttpResponse(response, mimetype="application/json")
4

1 回答 1

1

我在代码片段中看到了两个问题。

首先,这里的逻辑问题:

for donation in donations:
    ##helper['donation_date'] = donation.date
    helper['donation_amount'] = donation.amount

如果捐赠有多个元素,那么您最终将只得到列表中的最后一个元素,因为您donations每次都在循环并分配值 to helper

我想你想计算总金额,你可以这样做:

helper['donation_amount'] += donation.amount

二、线路:

data = [ 
    'participant_specific_donation': info,
    'participant_specific_milestone': info1 
]

会给你一个语法错误。

看来你这里需要一本字典。初始化字典的正确方法是使用{ }大括号:

data = { 
    'participant_specific_donation': info, 
    'participant_specific_milestone': info1
}

如果你想把所有的捐款都放在一个地方,你可以先列出一个清单:

donation_amount = [donation for donation in donations]

然后将其分配给辅助字典:

helper['donation_amount'] = donation_amount
于 2013-02-10T02:33:37.160 回答