Skip to main content

Querying tables linked via foreign keys

A student was trying to display data from both her parent and child tables that were linked by foreign key. I played around with it and found 2 ways I can do this. 

The models(I took out most of the fields for this post because it was unnecessary for this explanation):
class Owner(models.Model):
owner_fname = models.CharField('First Name', max_length=50, blank=False, null=False)

Owner=models.Manager()


class PlayTime(models.Model):
dog_name = models.CharField(max_length=50, blank=False)
owner = models.ForeignKey(Owner, on_delete=models.CASCADE, blank=False, null=False)

PlayTime=models.Manager()

This first method involves multiple queries to the database. The second method involves a single query, and fewer lines of code. It is the equivalent of an inner join. I didn't include the context and the return statement, which are necessary, of course, if you plan to pass these variables on to the template.
def details(request, pk):
#============== METHOD 1: query database multiple times ===============#
get_posts = get_object_or_404(PlayTime, pk=pk)
print(get_posts.owner_id)
lookup_id = get_posts.owner_id #get foreign key
get_owner= get_object_or_404(Owner, pk= lookup_id) #pass foreign key to second db query
print(get_owner.owner_fname)

# ============== METHOD 2: inner join =================#
details = PlayTime.PlayTime.select_related('owner').get(id=pk)
print(details.owner.owner_fname)
# print(details.values())
 If you wanted to join all the data in both tables, you can also do so and get a queryset. In that case, you would just type: 
details = PlayTime.PlayTime.select_related('owner')

Disclaimer: I'm not sure if this is the best way to do this, but this is what I figured out from looking at documentation online. 

Comments

Popular posts from this blog

Snakes and ladders

I've started on my Python course. So far, the code has been familiar because the first few basic codes are similar to Javascript. And then modules happened. Confusion and despair! What is the world is 'if __name__ == "__main__": ' and why must I reach this section of my course on a public holiday when none of the instructors are in :( Stack overflow to the rescue, providing me a lifeline while I was drowning in a pit of serpents. I feel eternally indebted to a particular Mr Fooz.  Picture from  here From my understanding, when the Python interpreter reads a source file, it first sets the variable __name__ and then it executes all the code in the file. If that particular file that you are running(i.e. your module) is the main program, the interpreter will assign '__name__ = "__main__" '. Thereafter, any code in the aforementioned 'if' statement is run. If you have, instead, imported a module, the interpreter assigns '__name__ ...

I gotta feeling...

I've been helping a colleague with his portfolio site. He's making it retro video game themed at my suggestion. He found an interesting pixelated font called arcade classic  and used it for the headings on his page. Unfortunately, some of the letters almost overlapped, making it not quite readable. Before letter spacing I looked into typography ages ago and learnt about letter and word spacing and wondered if that was something that I could fiddle with using CSS. Turns out it is a property you can customise. I opened up Chrome Dev tools and added 3 pixels of letter spacing and it looked so much better. And there's letter spacing too, so that's pretty neat.  After letter spacing Can't say CSS is my favourite thing ever but it's always nice to learn something new in unexpected ways.

Fizzbuzz

I was today years old when I found out what fizzbuzz was. Yes, I'm late to the party. I was in an interview where the interviewer mentioned that ordinarily they would ask interviewees in for a round of fizzbuzz challenges, as I know. Actually sir, no, I don't know 👀 But he sounded so certain that I must surely know what it is that I was afraid to say anything so I did what I always do when I panic. Look right back saying not a word. I googled this mysterious fizzbuzz problem:  It looks pretty easy. I don't think he meant this actual problem, but problems like this. Because this problem is way too easy to be an actual problem someone asks in an interview. I decided to work on it for fun:  Yup. Super easy. I wish this is all I were asked in an interview 😄