Home > Mobile >  How to access a value in a table connected by a Foreign Key
How to access a value in a table connected by a Foreign Key

Time:02-08

Currently I have a table called Load that has a relationship to a table called Container through a Foreign Key called Container_ID (the FK is just an integer). The foreign key lives in the Load table. Each row in the Load table has a Container_ID.

The table Container has a column called Container_Name.

What I want to do is to grab all rows from the Load table, and be able to tell what the actual container name is. Not the Container_ID, but the Container_Name that's in the Container table.

I tried doing something like var = Load.objects.values_list('container_ID') but that only returns the actual foreign key integer, and I'm not sure how to take it that one step further to dive into the actual Container table to grab that Container_Name field.

Just for clarification, I am working with Python and MYSQL here.

CodePudding user response:

You can access the Container name through field lookup. You can see it here in the docs. In your example, you can access it as var=Load.objects.values_list('container__Container_Name') The generic syntax for this is var=ModelName.objects.value_list('foreign_key_field__field_in_related_table')

  •  Tags:  
  • Related