gpt4 book ai didi

python - 如何显示查询集列表?

转载 作者:行者123 更新时间:2023-12-01 07:27:04 24 4
gpt4 key购买 nike

我正在为游戏锦标赛创建网站。我有专门的查询集。我想在一页上显示球队的名称及其球员。

我尝试使用“get_queryset()”函数,但我不明白到底是什么。可能模板部分有错误。

模型.py

from django.db import models

class TestTeam(models.Model):
name = models.CharField(max_length=30, default='Team')
slug = models.SlugField(max_length=5)

def __str__(self):
return self.name


class TestPlayer(models.Model):
name = models.CharField(max_length=100, default='Player')
nick = models.CharField(max_length=20, default='Nickname')
team = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, default='Team')
#photo = models.ImageField(upload_to='', null=True)
No = 'N'
Yes = 'Y'
STANDIN_CHOICES = [
(Yes, 'Yes'),
(No, 'No'),
]
standin = models.CharField(max_length=5, choices=STANDIN_CHOICES, default=No)
slug = models.SlugField(max_length=20, default=nick)

def __str__(self):
return self.name


class TestMatch(models.Model):
name = models.CharField(max_length=100, default='Match')
leftTeam = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, related_name='+', default='Left Team')
rightTeam = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, related_name='+', default='Right Team')
slug = models.SlugField(default=str(name))

def __str__(self):
return (str(self.leftTeam) +" - "+ str(self.rightTeam))

url.py

from . import views
from django.urls import path

urlpatterns = [
path('', views.TestView.as_view(), name='home'),
path('<slug:slug>/', views.MatchView.as_view(), name='match'),
]

View .py

from django.views.generic import ListView, DetailView
from . import models
from django.shortcuts import get_list_or_404

class TestView(ListView):
model = models.TestMatch
template_name = 'home.html'

class MatchView(DetailView):
model = models.TestPlayer
template_name = 'match.html'

def get_queryset(self):
queryset = super().get_queryset()
if 'slug' in self.kwargs:
team_slug = self.kwargs['slug']
TEAM = get_list_or_404(models.TestTeam, slug=team_slug)
queryset = queryset.filter(team=TEAM[0])
return queryset

显示HTML(match.html)

{% extends 'base.html' %}
{% block content %}

{% regroup object_list by team as player_list %}
{% for player in player_list %}
<h3>{{ player.name }}</h3>
{% endfor %}
{% endblock %}

我希望球队及其球员显示在一页上。

最佳答案

{% regroup .. %} tag [Django-doc]意味着 player_list 不包含 player 列表:它包含多组球队,并且每个组中都有一个球员列表。

因此,您将其呈现为:

{% regroup object_list by team as <b>team_list</b> %}
{% for <b>team in team_list</b> %}
<h3>{{ team.<b>grouper</b> }}</h4>
{% for <b>player in team.list</b> %}
<h4>{{ <b>player</b> }}</h4>
{% endfor %}
{% endfor %}

这里的grouper因此是对Team的引用,并且team.list将包含相关的可迭代对象玩家

关于python - 如何显示查询集列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57395553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com