Im building a search form in django, Im doing it with filter querysets, this form is like a "advance search form", I mean, form could has more than two inputs, but problem is that each input corresponding of a field of different model, I have this and works fine if the form only has one input for one model:
def post(self,request,*args,**kwargs):
buscar_predio = request.POST['nombre_predio']
query1 = InfoPredioGeneral.objects.filter(nombre_predio__iexact=buscar_predio)
if query1:
ctx = {'predio':query1}
return render(request,'resultados_busqueda.html',ctx)
else:
return render(request,'resultados_busqueda.html')
If I have this models:
class InfoPredioGeneral(models.Model):
nombre_predio = models.CharField(max_length=30)
class Propietario(models.Model):
predio = models.ForeignKey(InfoPredioGeneral,blank=True,null=True,related_name='predio_propietario+')
tipo_identificacion = models.ForeignKey(TipoIdentificacion,related_name='tipo identificacion+',blank=True,null=True)
In the post method how can I search in the same form a InfoPredioGeneral
and Propietario
? For example filter where nombre_predio is exact to "predio proof" and where tipo_identificacion
is exacto to "123"? As you can see Propietario
has a ForeignKey
to InfoPredioGeneral
you are looking for a many-to-one relationship
https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_one/
you already set the related_name to "predio_propietario+" and with the '+' at the end this means there is no backwards relation to this model
there is you example:
Extra:
queryset will look like this: