Im building an advanced search form. Im doing it with filter querysets, but I need to pass it two or more models to the form. How can I achieve it? Until now, I have this but with some troubles:
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')
Question 1:
query1
queryset works fine but has a little error, as you can see, it calls two fields but when I make a search by the two fields only take one, I mean in nombre_predio
I put a valid query and in matricula_inmobiliaria
a data that does not exist, but anyway give the result. It supposed if I fill the two fields and one of two does not exists, don't has to show any result. How can I valid this?
Question 2:
How can I join query2
in predio
?
Note: Propietario has a ForeignKey to InfoPredioGeneral. So, I don't know if maybe to render the result in the template has to call a Lookup Field
Here is How I render the result in the template
{% for i in r %}
<tr>
<td>{{i.nombre_predio}}</td>
<td>{{i.coordenada_n}}</td>
<td>{{i.coordenada_w}}</td>
</tr>
{% endfor %}
My models:
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)