【问题标题】:Django queryset with variable value具有变量值的 Django 查询集
【发布时间】:2018-04-30 10:28:15
【问题描述】:

我正在 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)

但是django在下面一行返回错误

Q(p_type__contains=s_type))

我有动态单选按钮,其中 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).

变量查询不可行吗?还有其他方法吗?

型号:

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)

【问题讨论】:

  • 你得到什么错误?
  • 你不应该使用p__type__contains吗?
  • 我在 /fp/ 处收到错误 FieldError 无法将关键字“p_type”解析为字段。选择有:P_63、P_64 等。
  • 我写的是 p_type 而不是 p__type。我应该改变吗?
  • 请展示您的型号。我假设,您过滤的不是您需要的查询集。

标签: python django variables django-queryset


【解决方案1】:

如果p_type持有你要查询的字段名,那么你可以这样做:

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

【讨论】:

  • 我还找到了另一种可以按以下方式使用的解决方案:queryset_find = queryset_list.filter( Q(**{p_type: s_type}))
猜你喜欢
  • 2018-04-01
  • 2018-09-29
  • 2015-08-25
  • 2011-09-08
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 2011-02-02
  • 2014-07-08
相关资源
最近更新 更多