简体   繁体   中英

Learning multi tables joining info django

While i find this post Django views.py Version of SQL Join with Multi Table Query helpful. It does not seem to help me with understading joining tables. I had earlier help on a question and I thought I got it. I am trying to do the following show (current) players on the Boston Penguins.

Code I have currently trying to pull it is

Player.objects.filter(team__all_teams__contains='boston', player__curr_team__contains="Penguins")

Which by reasoning anyway puts me in the Player.objects of my model and should be filtering from my team all the teams with Boston which there is on and then should pull all the current players for that team.

Even better than just giving me an answer is a link to a video or document that better explains this so I can study it better to learn the call functions.

Models.py

from django.db import 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")

views.py  only line i need help with rest works fine if i take out that line

"bostonp" : Player.objects.filter(team__all_teams__contains='boston', player__curr_team__contains="Penguins") ,


index.html   only section that doesnt work take it out and it works

<h5>Question 2</h5>
         {% for whatever in bostonp %}
        <li>{{whatever.team_name}}</li>
        {% endfor %}
        </ol>

Try this (this will fetch player instances):

bostonp = Player.objects.filter(curr_team__team_name__contains='Penguins')

And then in your template:

{% for player in bostonp %}
    <li>{{ player.first_name }} {{ player.last_name }}</li>
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM