Filter queryset between two or more models for search form in django

283 views Asked by At

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

1

There are 1 answers

3
Ben Hsieh On BEST ANSWER

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:

queryset = Propietario.objects.filter(predio__nombre_predio__iexact=request.POST['nombre_predio'])

Extra:

class C(models.Model):
    c_text = models.CharField(max_length=100)

class B(models.Model):
    b_text = models.CharField(max_length=100)

class A(models.Model):
    b = models.ForeignKey(B)
    c = models.ForeignKey(C)

queryset will look like this:

queryset = A.objects.filter(b_btext__isexact="your b text", c_ctext__isexact="your c text")