query foreign key relationships
Date: March 18th 2016
Last updated: March 18th 2016
This is a side note, I've gone back to the django shell to clarify the relationships between tables. All of the examples contain the same database and record entries seen previously in this chapter.
Shell
python3 manage.py shell
Import models
from surferprofile.models import *
Find a record (e.g. beach)
b = Beach.objects.get(pk=1)
b
#<Beach: Lyall Bay>
Query foreign key
b.wave_set.all()
[<Wave: Main Beach>, <Wave: The Wall>]
Assign another record (e.g. surfer)
s = Surfer.objects.get(pk=1)
s
#<Surfer: Ray Blick>
Query many to many relationship (e.g. tricks)
s.tricks.all()
#[<Trick: Roundhouse cutback>, <Trick: Head dip shampoo>]
Query many to many relationship (e.g. favourite wave)
s.favwave.all()
#[<Wave: Main Beach>, <Wave: Seal Rocks>]
Return all values in many to many relationship
s.favwave.values_list()
#[(4, 'BB', 'TU', 'Main Beach', 2), (5, 'PB', 'CR', 'Seal Rocks', 3)]
Return a single tuple from the list
s.favwave.values_list()[1] #<=== second tuple of the list
#(4, 'BB', 'TU', 'Main Beach', 2)
Return single element
s.favwave.values_list()[1][2]
#'CR'