0

I am trying to get the field value of a joined table. This is the generated sql of ORM query.

SELECTsubnets_subnetoption.id, subnets_subnetoption.subnet_id,subnets_subnetoption.value_id, subnets_subnet.id,subnets_subnet.parent_id, subnets_subnet.base_address,subnets_subnet.bits, subnets_subnet.bcast_address,subnets_subnet.is_physical, subnets_subnet.name,subnets_subnet.responsible, subnets_subnet.building_floor,subnets_subnet.comments, subnets_subnet.vlan_common_name,subnets_subnet.creation_date, subnets_subnet.modification_date,subnets_subnet.sec_level, subnets_subnet.confid,subnets_subnet.access_type, subnets_subnet.zone_type,options_value.id, options_value.content,options_value.comment, options_value.option_id,options_option.id, options_option.name,options_option.required, options_option.scope_id,options_scope.id, options_scope.nameFROMsubnets_subnetoptionINNER JOIN subnets_subnetON (subnets_subnetoption.subnet_id= subnets_subnet.id) INNER JOINoptions_valueON (subnets_subnetoption.value_id=options_value.id) INNER JOIN options_optionON (options_value.option_id= options_option.id) INNER JOINoptions_scopeON (options_option.scope_id=options_scope.id) WHERE subnets_subnetoption.subnet_id` = 1

   SubnetOption.objects.select_related().filter(subnet_id=subnet['id']).query

I need only options_value.content and options_option.name, but query set i giving the subnetoption table values only. How can I get the joined tables values. I am new to django

Anish
  • 4,262
  • 6
  • 36
  • 58

2 Answers2

1
 SubnetOption.objects.filter(subnet_id=subnet['id']).select_related().values('options_value__content')

or

SubnetOption.objects.filter(subnet_id=subnet['id']).select_related('modelname_in_wholelowercase')

try this once

Exprator
  • 26,992
  • 6
  • 47
  • 59
  • the entire query got changed SELECT `options_value`.`content` FROM `subnets_subnetoption` INNER JOIN `options_value` ON (`subnets_subnetoption`.`value_id` = `options_value`.`id`) WHERE `subnets_subnetoption`.`subnet_id` = 1 – Anish Jun 23 '17 at 04:33
  • second one is also not working . entire join relation is removed – Anish Jun 23 '17 at 04:37
0

You can use raw query of django, which means you can put SQL query as it is, for reference

Raw sql queries in Django views

Sanket
  • 744
  • 7
  • 22