在一个查询集中过滤两个模型-高级搜索django



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

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')

问题1:

query1 queryset工作得很好,但有一点错误,正如你所看到的,它调用两个字段,但当我通过两个字段只取一个进行搜索时,我的意思是在nombre_predio中我放置了一个有效的查询,在matricula_inmobiliaria中一个不存在的数据,但无论如何给出结果。它假设,如果我填写两个字段,其中一个不存在,不需要显示任何结果。我怎样才能使它有效呢?

问题2:

如何在predio中加入query2

注意:Propietario对InfoPredioGeneral有一个外键。所以,我不知道是否要在模板中呈现结果需要调用查找字段

下面是我在模板 中渲染结果的方法
 {% 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)

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

 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>

最新更新