基于列表值的Django过滤

时间:2014-03-21 09:34:33

标签: python django django-views django-rest-framework

我的JSON数据采用这种格式..

[
    {
        "id": "532befe4ee434047ff968a6e",
        "company": "528458c4bbe7823947b6d2a3",
        "values" : [
                        {
                             "Value":"11",
                             "uniqueId":true
                        },
                        {
                             "Value":"14",
                             "uniqueId":true
                        },
                     ]
     },
     {
        "id": "532befe4ee434047ff968a",
        "company": "528458c4bbe7823947b6d",
        "values" : [
                        {
                             "Value":"1111",
                             "uniqueId":true
                        },
                        {
                             "Value":"10",
                             "uniqueId":true
                        },
                     ]
     }

]

如果我想根据公司字段进行过滤,那么就可以这样做。

qaresults = QAResult.objects.filter(company= comapnyId)

它给了我第一个列表字典

但是,如果我想根据值列表""值"来过滤第一本字典的价值键?

1 个答案:

答案 0 :(得分:0)

我不是100%确定你想要什么,但从我理解你的问题, 试试这个解决方案:

import json
json_dict = json.loads('[{"id": "532befe4ee434047ff968a6e","company": "528458c4bbe7823947b6d2a3","values": [{"Value": "11","uniqueId": true},{"Value": "14","uniqueId": true}]},{"id": "532befe4ee434047ff968a","company": "528458c4bbe7823947b6d","values": [{"Value": "1111","uniqueId": true},{"Value": "10","uniqueId": true}]}]')

expected_values = []

js = json_dict[0]
for key,value in js.items():
    if key == 'values':
        expected_values.append(value[0]['Value'])

然后

qaresults = QAResult.objects.filter(company__id__in = expected_values)