加入两张桌子django新手问答
mysqllite表加入django对我来说是新事物。我可以在一张桌子上查询。在某种程度上是通过原始mysql加入的。我需要的是一个如何将表编码到一起的示例,即在模型下面,我的项目的第一个问题是找到大西洋会议中的所有团队 我有 鉴于此加入两张桌子django新手问答,django,python-2.7,django-models,Django,Python 2.7,Django Models,mysqllite表加入django对我来说是新事物。我可以在一张桌子上查询。在某种程度上是通过原始mysql加入的。我需要的是一个如何将表编码到一起的示例,即在模型下面,我的项目的第一个问题是找到大西洋会议中的所有团队 我有 鉴于此 "atlanticsoccer": League.objects.filter(name__contains="atlantic") this in html <h5>Question 1</h5>
"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>
首先,让所有拥有大西洋联盟的球队:
atlanticsoccer = Team.objects.filter(league__name__contains='atlantic')
然后在模板中迭代并打印所需内容:
<ul>
{% for team in atlanticsoccer %}
<li>{{team.location}}</li>
<li>{{team.team_name}}</li>
<li>{{team.league.name}}</li>
<li>{{team.league.sport}}</li>
{% endfor %}
</ul>
泰,这就是我正在寻找的例子,现在我可以做剩下的事了。祝你好运,我的朋友。快乐编码!如果你仍然在那里,是的,这收集了我需要的所有数据,这是不是有一个技巧,只是把球队从一个特定的运动和联盟?当然。试试这个:Team.objects.filterleague\uuuuuu name\uuuuuuu contains='atlantic',league\uuuuuu sport\uuuuuuuuuuu contains=some\u sport再次感谢我会找出html。谢谢你的帮助