动态查询获取python后的数据

时间:2013-10-09 13:43:01

标签: python django django-queryset

当我将数据发布到查询时,我正在执行以下操作:

fields = [
'name',
'surname',
'weight',
'height',
'position',
'agent',
'nationality',
'shirt_name',
'shirt_number',
'preferred_foot',
]

if request.method == 'POST':

    filter_spec = None
    for fld_name in fields:
        value = request.POST.get(fld_name, None)
        if value is not None:
            if fld_name == 'position':
                fld_name = 'position__in'
                value = Position.objects.filter(name=value)
            if fld_name == 'agent':
                fld_name = 'entrepreneur__in'
                value = Entrepreneur.objects.filter(name=value)
            if filter_spec is None:
                filter_spec = Q(**{fld_name: value})
            else:
                filter_spec &= Q(**{fld_name: value})
    players = Player.objects.filter(filter_spec) if filter_spec else Player.objects.none()
    result = [p.get_json() for p in players]
    py_resp = {
        'meta': {
            'total_count': len(result),
        },
        'objects': result,
    }
    json_resp = json.dumps(py_resp)
    return HttpResponse(json_resp, content_type='application/json')

定位查询如下:

Player.objects.filter(position__in=Position.objects.filter(name=positionpost))

所以我做了它,因为它在顶部,我无法在国籍的代码中实现它,因为查询是这样的:

Player.objects.filter(country__in=Country.objects.filter(nationality__in=Nationality.objects.filter(name='Espanhola')))

而且我不确定如何将其放在上面的代码中 有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

您的查询都可以大大简化。第一个应该是:

Player.objects.filter(position__name=positionpost)

和第二个:

Player.objects.filter(country__nationality__name='Espanhola')

这些通常也会更有效率,因为它们正在进行JOIN而不是子查询。