标签:django orm
django orm 关联表数据,即sql的多表查询
例如两个表:
Apply表中定义了字段position为foreignkey指向job表的id字段,
1.通过job表查找子表apply的字段信息:
job.objects.values( ‘id‘, ‘job_type‘, ‘apply__date_created‘)
连接符为小写的子表tablename+双下线+子表字段名即:apply__date_created 表示寻找Apply表中的date_created字段
等价于后台的SQL:
SELECT `job`.`id`, `job`.`job_type`, `apply`.`date_created` FROM`job` LEFT OUTER JOIN `apply` ON ( `job`.`id` = `apply`.`position_id` )
2.加filter方法筛选子表字段:
JobInformation.objects.filter(apply__name=’zhang’).values( ‘id‘, ‘job_type‘, ‘apply__date_created‘)
等价于后台的SQL:
SELECT `job`.`id`, `job`.`job_type`,`apply`.`date_created` FROM `job` LEFT OUTER JOIN `apply` ON ( `job`.`id` =`apply`.`position_id` ) where apply.name=’zhang’
3. 再加一个user表,定义job的user字段foreignkey指向user表的id字段,通过表job查询user表的其他字段,三表查询
Job.objects.filter(apply__name=’zhang’).values( ‘id‘, ‘job_type‘, ‘apply__date_created‘,user__address’)
user__address 外键字段名+双下划线+主表字段名
等价于后台的SQL:
SELECT `job`.`id`,`job`.`job_type`, `apply`.`date_created`,user.address FROM `job` inner JOIN `apply` ON (`job`.`id` = `apply`.`position_id` ) inner JOINuser on job.user=user.id where apply.name=’zhang’
标签:django orm
原文地址:http://3379770.blog.51cto.com/3369770/1883651