加入两张桌子django newbie qustion

时间:2017-03-19 16:08:46

标签: django python-2.7 django-models

加入django的mysqllite表对我来说是新手。我可以在一张桌子上查询得很好。并且有点通过原始mysql加入。我需要的是一个如何对表格进行编码的示例,即在模型下方,我项目的第一个问题是找到所有在大西洋会议中的团队

我有     这在视野中

  "atlanticsoccer": League.objects.filter(name__contains="atlantic")

 this in html
    <h5>Question 1</h5>
                {% for whatever in atlanticsoccer %}
                <li>{{whatever.name}}</li>
                <li></li>
                {% endfor %}
                </ol>

which gives me all my Atlantic conference leauges. But i can't seem to find an example of how to join the teams by id . I have linked below the models view If i can get an example of how to do the first I can figure out the html. Thanks in advance for helping a new coder.

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

from django.shortcuts import render, redirect
from .models import League, Team, Player

from . import team_maker

def index(request):
    context = {
        "leagues": League.objects.all(),
        "teams": Team.objects.all(),
        "players": Player.objects.all(),

        "atlanticsoccer": League.objects.filter(name__contains="atlantic")


    }
    return render(request, "leagues/index.html", context)

def make_data(request):
    team_maker.gen_leagues(10)
    team_maker.gen_teams(50)
    team_maker.gen_players(200)

    return redirect("index")

index.html

    <h5>Question 1</h5>
        {% for whatever in atlanticsoccer %}
        <li>{{whatever.name}}</li>
        <li></li>
        {% endfor %}
        </ol>

1 个答案:

答案 0 :(得分:1)

首先获取==的所有teams,其名称为&#34; atlantic&#34;:

league

然后在模板中迭代它们并打印您想要的任何内容:

atlanticsoccer = Team.objects.filter(league__name__contains='atlantic')