使用 Q 和具有不同值的多个字段的 Django 过滤器

Django filter using Q and multiple fields with different values

我正在尝试生成满足以下过滤器查询的结果:

indicators = request.GET.getlist('indicators[]')
fmrprofiles = FMRPriority.objects.all()
q_objects = Q()
obj_filters = []
for indicator in indicators:
    split_i = indicator.split('_')
    if len(split_i) == 5:
        if not any(d['indicator'] ==  split_i[1] for d in obj_filters):
            obj_filters.append({
                'indicator': split_i[1],
                'scores': []
            })

        for o in obj_filters:
            if split_i[1] == o['indicator']:
                o['scores'].append(int(split_i[4]))

for obj in obj_filters:
    print (obj['scores'])
    q_objects.add(Q(pcindicator__id = int(obj['indicator'])) & Q(score__in=obj['scores']), Q.AND)
print (q_objects)
fmrprofiles = fmrprofiles.values('fmr__id','fmr__road_name').filter(q_objects).order_by('-fmr__date_validated')
print (fmrprofiles.query)

基本上,indicators 是一个列表,例如['indicator_1_scoring_1_5', 'indicator_1_scoring_1_4', 'indicator_2_scoring_2_5']

我想用以下字段过滤 FMRPriority:

例如pcindicator 等于 1,所选分数为 5,4..另一个选择 pcindicator 等于 2,所选分数为 3。 查询 q_objects.add(Q(pcindicator__id = int(obj['indicator'])) & Q(score__in=obj['scores']), Q.AND) returns 空集..我也尝试了原始 sql,结果相同。

型号:

class FMRPriority(models.Model):

    fmr = models.ForeignKey(FMRProfile, verbose_name=_("FMR Project"), on_delete=models.CASCADE)
    pcindicator = models.ForeignKey(PCIndicator, verbose_name=_("Priority Indicator"), on_delete=models.PROTECT)
    score = models.FloatField(_("Score"))

我通过使用 OR 来解决这个问题并计算 id 的出现,然后排除那些不等于过滤器长度的:

for obj in obj_filters:
    print (obj['scores'])
    q_objects.add(
        (Q(fmrpriority__pcindicator__id = int(obj['indicator'])) & Q(fmrpriority__score__in=obj['scores'])), Q.OR
    )

fmrprofiles = fmrprofiles.values(*vals_to_display).filter(q_objects).annotate(
        num_ins=Count('id'),
        ...
    )).exclude(
        ~Q(num_ins = len(obj_filters))
    ).order_by('rank','road_name')