0

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

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')))

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

4

1 回答 1

0

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

Player.objects.filter(position__name=positionpost)

第二个:

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

这些通常也会更有效,因为它们执行的是 JOIN 而不是子查询。

于 2013-10-09T13:50:00.540 回答