【问题标题】:Filter with two models in one queryset - Advanced search django在一个查询集中使用两个模型进行过滤 - 高级搜索 django
【发布时间】:2015-07-29 07:57:53
【问题描述】:

我正在构建一个高级搜索表单。我用过滤器查询集来做,但我需要将两个或多个模型传递给表单。我怎样才能实现它?到目前为止,我有这个但有一些麻烦:

def post(self,request,*args,**kwargs):
        buscar_predio = request.POST['nombre_predio']
        matricula = request.POST['matricula_mobiliaria']
        propietario = request.POST['propietario']
        query1 = Q(nombre_predio__iexact=buscar_predio)| Q(matricula_inmobiliaria__iexact=matricula)
        query2 = Propietario.objects.filter(primer_nombre=propietario)
        predio = InfoPredioGeneral.objects.filter(query1)
        print(predio)
        if predio:
            ctx  = {'r':predio}
            return render(request,'resultados_busqueda.html',ctx)
        else:
            return render(request,'resultados_busqueda.html')

问题一:

query1 queryset 工作正常但有一点错误,如您所见,它调用了两个字段,但是当我通过这两个字段进行搜索时只取一个,我的意思是在nombre_predio 我输入了一个有效的查询和在matricula_inmobiliaria 一个不存在的数据,但无论如何给出结果。它假设如果我填写两个字段并且两个字段之一不存在,则不必显示任何结果。我怎样才能验证这一点?

问题 2:

如何在predio 中加入query2

注意:Propietario 有一个指向 InfoPredioGeneral 的 ForeignKey。所以,我不知道在模板中渲染结果是否必须调用查找字段

这是我如何在模板中呈现结果

 {% for i in r %}
        <tr>
            <td>{{i.nombre_predio}}</td>
            <td>{{i.coordenada_n}}</td>
            <td>{{i.coordenada_w}}</td>
        </tr>
{% endfor %}

我的模型:

class InfoPredioGeneral(models.Model):
    user = models.ForeignKey(User)
    fecha = models.DateField(auto_now=True)
    coordenada_n = models.DecimalField(max_digits=100,decimal_places=8,blank=True,null=True)
    coordenada_w = models.DecimalField(max_digits=100,decimal_places=8,blank=True,null=True)


class Propietario(models.Model):
    predio = models.ForeignKey(InfoPredioGeneral,blank=True,null=True,related_name='predio_propietario+')
    numero_identificacion = models.CharField(max_length=100,blank=True,null=True)
    primer_nombre = models.CharField(max_length=100)

【问题讨论】:

  • 模型是什么样子的?
  • @f43d65 我已经用模型编辑了我的问题

标签: django django-queryset searchqueryset


【解决方案1】:

对于您的查询 1,您使用的是 or,这将为您提供验证两个条件之一的条目。如果要验证这两个条件,请使用和

 query1 = Q(nombre_predio__iexact=buscar_predio)& Q(matricula_inmobiliaria__iexact=matricula)

我不确定加入,但您可以直接在模板中访问外键。因此,如果您有正确的 Propietarop 集,您可以直接在模板中访问 InfoPredioGeneral 而无需其他查询。像这样:

<td>{{i.predio.coordenada_n}}</td>
<td>{{i.predio.coordenada_w}}</td>

【讨论】:

  • 谢谢,但连接的解决方案不适用,因为如果在模板中我使用 i.predio.coordenada_n 只是显示在我搜索了模型 Propietario,但如果我搜索InfoPredioGeneral 不显示它,反之亦然。
  • 如果你想从 infoprediogeneral 中查找propietario,你也可以从你的模板中访问它。像这样:i.propietario_set.all。这将提供所有具有此特定 infoprediogeneral 作为外键的 propietario。你也可以滚动它。但我不确定,因为在您的模板中,您的模型中没有对 nombre_predio 的调用调用,因此这部分令人困惑。
猜你喜欢
  • 2023-03-17
  • 2015-08-27
  • 2019-03-03
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
  • 2018-08-27
相关资源
最近更新 更多