简体   繁体   English

具有变量值的Django查询集

[英]Django queryset with variable value

I am writing dynamic filters in django for my database where I am using the below code where I have 2 variables(p_type,s_type): 我在django中为我的数据库编写动态过滤器,我使用下面的代码,我有2个变量(p_type,s_type):

        p_type=[]
        s_type=[]
        query = request.GET.get("q")
        p_type =request.GET.get("p_type")
        s_type = request.GET.get("s_type")
        #messages.add_message(request, messages.INFO, p_type)
        #messages.add_message(request, messages.INFO, s_type)
        if query:
            queryset_find = queryset_list.filter(
                Q(FP_Item__contains=query))
            context = {'object_list': queryset_find}
            return render(request, 'index.html', context)
        elif p_type:
            queryset_find = queryset_list.filter(
                Q(p_type__contains=s_type))
            context = {'object_list': queryset_find}
            return render(request, 'index.html', context)
        else:
            context = {'object_list': queryset}
            return render(request, 'index.html', context)

but django returns error at below line 但是django在下面的行返回错误

Q(p_type__contains=s_type))

I have dynamic radio button where the value of p_type matches with my database but even though I am receiving the following error: 我有动态单选按钮,其中p_type的值与我的数据库匹配,但即使我收到以下错误:

Exception Type: FieldError
Exception Value:    
Cannot resolve keyword 'p_type' into field. Choices are: ... (same choices which I am using with my database).

Isn't it doable with variable query ? 变量查询不可行吗? Any other methods ? 还有其他方法吗?

model: 模型:

class RFP(models.Model):
    FP_Item = models.TextField(max_length=1500)
    P_63 = models.TextField(max_length=1000)
    P_64 = models.TextField(max_length=1000)

If p_type holds the name of the field you want to query, then you can do: 如果p_type包含您要查询的字段的名称,则可以执行以下操作:

elif p_type:
    kwargs = {
        '{}__contains'.format(p_type): s_type
    }
    queryset_find = queryset_list.filter(Q(**kwargs))
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM