Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

251
Views
Python/Django Trying to continually reference foreign keys in multiple classes and be able to print out information from views

I know how to reference a single foreign key but when it comes to a foreign key inside another foreign key, I'm lost. I can't think of the correct logic to make this work, which makes me think there's a special logic that applies to this.

What I've tried:

    b2=[]
    league = League.objects.get(name='International Collegiate Baseball Conference')
    team = league.teams.all()
    for b in team.curr_players.all():
       b2.append(b.first_name + b.last_name)

From my models:

class League(models.Model):
    name = models.CharField(max_length=50)
    sport = models.CharField(max_length=15)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Team(models.Model):
    location = models.CharField(max_length=50)
    team_name = models.CharField(max_length=50)
    league = models.ForeignKey(League, related_name="teams")

class Player(models.Model):
    first_name = models.CharField(max_length=15)
    last_name = models.CharField(max_length=15)
    curr_team = models.ForeignKey(Team, related_name="curr_players")
    all_teams = models.ManyToManyField(Team, related_name="all_players")
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

found the answer, i had to do a for loop to iterate through what i was receiving from league.teams.all() - which was a team object and then set the iterations equal to a variable and set another iteration equal to variable.related_name.all()

b2=[]
league = League.objects.get(name='International Collegiate Baseball Conference')
team = league.teams.all()
for a in team:
    players = a
    for b in players.curr_players.all():
        b2.append(b.first_name + b.last_name)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!