Django - how to make queries in several tables (join)?

0

Good morning. I am passing a project from Codeigniter to Django and I have had problems understanding queries in several tables, and with several parameters. The data model that I have is the following:

class Municipios(models.Model):
    codmunicipio        = models.IntegerField(primary_key = True)  
    coddepartamento     = models.ForeignKey(Departamentos, on_delete =  models.PROTECT, db_column = 'coddepartamento')  
    nombre              = models.CharField(max_length = 50)

class Telefonos(models.Model):  
    id                  = models.AutoField(primary_key = True)  
    codmunicipio        = models.ForeignKey(Municipios, on_delete = models.PROTECT, db_column = 'codmunicipio')  
    nombre              = models.CharField(max_length = 250)  
    telefono            = models.BigIntegerField(default = 0)  
    telefono2           = models.BigIntegerField(default = 0)  
    celular             = models.BigIntegerField(default = 0)  
    celular2            = models.BigIntegerField(default = 0)  
    email               = models.EmailField(max_length = 60, default = '')

And I want to make a query like this, where the operator "o" is used according to several fields with string comparison:

select t.telefono,t.celular, t.nombre, m.nombre as municipio  
from telefonos as t, municipios as m 
where t.codmunicipio= m.codmunicipio and (t.telefono like '%$stelefono%' or t.celular like '%$stelefono%' )  
union all select t.telefono,t.celular, t.nombre, m.nombre as municipio  
from telefonos as t, municipios as m 
where t.codmunicipio= m.codmunicipio and (t.telefono like concat('%',right('$stelefono',7)) or t.celular like concat('%',right('$stelefono',7))  ) 
limit 30 offset $registro

The question is oriented, how to make a query with several tables, where there is a join. In Django it is easy to make queries from a table, but I have difficulty when there are several

    
asked by Jairo Marin 20.07.2016 в 17:37
source

1 answer

1

If the doubt comes from the use of the operator or . You can use the class Q :

from django.db.models import Q

Telefonos.objects.filter(Q(telefono=variable_telefono) | Q(celular=variabke_telefono))

The JOINs are executed by the ORM through the conditions you perform using the field that is an FK or using the notation __ :

Telefonos.objects.filter(codmunicipio__nombre='nombre_de_un_municipio')

This will do a JOIN with the model (table) Municipio using the nombre field as a reference

    
answered by 20.07.2016 в 18:23