Django 查询集在 if 之后为空,但它不应该



也许标题有点混乱,英语不是我的主要语言。我对此表示歉意。重点:我有一个可以活跃的客户表,简单的字段,上面写着"是"或"否"。因此,在html表单中,我有一个选择输入,其中包含3个选项:无关紧要(所有客户端,均值0(,是(活动客户端,值'yes'(,否(不活动,值'no'(。

事实是,当我想获得所有客户(活动和不活动(时,QuerySet变得空了,原因是我不了解的原因。

这是HTML表格的一部分:

<select name="ClienteActivo">
<option value="0" selected="selected">Indiferente</option>
<option value="Si">Si</option>
<option value="No">No</option>
</select>

这是视图:

def resultadosClienteAvanzadoView(request):
    #Here I retrieve all clients.
    clientes=ClientesCompradores.objects.all()
    #Active can be 0, yes or no. 0 means both, so no filter.
    active=request.GET.get('ClienteActivo')
    #If activo is not 0 then filter the clients.
    if active != 0:
        clientes=clientes.filter(nulo=active)
    #Create the context. Again, when active is 0 i want all the clients.
    context={
        'clientes':clientes,
        'cantidad':len(clientes)
    }
    return render(request,'catalog/resultadosClienteAvanzado.html',context)

如果有人需要更多信息,我没有任何问题。

我确定这是一个新秀错误,因为我仍在学习Django。

edit1:

django模型中的nulo就是这样:

nulo = models.CharField(max_length=10, blank=True, null=True)

这是我正在处理的遗产数据库,实际上是屁股的痛苦:/

预先感谢!

edit2:

中有一个错字
<option value="0" selected="selected">Indiferente</option>

该值实际上是0

edit3:毕竟是因为我将0评估为int而不是字符串。感谢Gytree指出的。

运行:

active = request.GET.get("ClienteActivo")
  • 如果用户选择" dandiferente",则活动为 '0'(cero 字符串(
  • 如果用户选择" Si"活动是'Si'
  • 并且如果用户选择"不"活动是'No'

然后问

active != 0:一直是真正的beacouse antive olny可以获得值('0','no','si'(

然后,当Python创建queryset时,请使用nulo = '0',而您没有nulo == '0'

的寄存器

然后,滤波器最多是:

if active != '0' 

if active in ('No', 'Si'):

假设 nulo是django booleanfield,请使用以下内容:

if active == 'Si':
    clientes = clientes.filter(nulo=True)
elif active == 'No':
    clientes = clientes.filter(nulo=False)

相关内容

最新更新