У меня есть модель по имени Сезон и модель по имени Игра:
# Season
class Season(models.Model):
teams = models.ManyToManyField('Team', related_name='season_teams', blank=True)
current = models.BooleanField(default=False)
year = models.PositiveIntegerField(
validators=[
MinValueValidator(2018),
MaxValueValidator(datetime.datetime.now().year)],
help_text = "Use the following format: <YYYY>", null=True, blank=True)
session = models.CharField(max_length=100, null=True, blank=True)
class Meta:
ordering = ['year', 'session']
def __str__(self):
session = self.session
year = str(self.year)
season = session + " " + year
return season
# Game
class Game(models.Model):
field_choices = FIELD_CHOICES
team_choices = TEAM_CHOICES
season = models.ForeignKey(Season, on_delete=models.CASCADE)
home_team = models.CharField(max_length=100, null=True, blank=True, choices=team_choices)
away_team = models.CharField(max_length=100, null=True, blank=True, choices=team_choices)
field = models.CharField(max_length=100, choices=field_choices, null=True)
date = models.DateTimeField(null=True, blank=True)
score = models.CharField(max_length=5, null=False, blank=True, default='')
tbd = 'TBD'
win = 'W'
draw = 'D'
loss = 'L'
result_choices = (
(tbd, 'TBD'),
(win, 'W'),
(draw, 'D'),
(loss, 'L'),
)
result = models.CharField(
max_length=3,
choices=result_choices,
default=tbd,
)
class Meta:
ordering = ['home_team', 'away_team', 'field','score', 'result']
def __str__(self):
return str(self.date)
def __unicode__(self):
return u'%s' % self.name
У меня есть представление Season, которое успешно запрашивает обе модели:
# Season
class Season(generic.ListView):
model = SeasonModel
template_name = 'team/season.html'
def get_queryset(self):
qs1 = SeasonModel.objects.filter(current=True)
qs2 = GameModel.objects.all().order_by('date')
queryset1 = sorted(chain(qs1))
queryset2 = sorted(chain(qs2),key=attrgetter('home_team'))
result = queryset1 + queryset2
return result
И затем шаблон, который должен отображать расписание команды, но он отображает его с дополнительной пустой строкой, как если бы я создал экземпляр Game с пустыми атрибутами. Это мой шаблон:
<div id = "schedule_header">
<h5 id = "datetime">Today's date is {% now "DATE_FORMAT" %}</h5>
{% for season in object_list %}
{% if season.current %}
<a href = ""><h5 id = "session">{{ season.year }} {{ season.session }} session</h5></a>
<a href = ""><h5 id = "season_history">Past Seasons</h5></a>
{% endif %}
{% endfor %}
</div>
<table class = "table" id = "e_schedule">
<thead>
<tr>
<th id = "thead"><h2>Week</h2></th>
<th id = "thead"><h2>Matchup</h2></th>
<th id = "thead"><h2>Field</h2></th>
<th id = "thead"><h2>Date/time</h2></th>
<th id = "thead"><h2>Score</h2></th>
<th id = "thead"><h2>Result</h2></th>
</tr>
</thead>
<tbody>
{% for game in object_list %}
<tr>
<th id = "counter"><p>{{ forloop.counter }}</p></th>
<th id = "matchup"><p>{{ game.home_team }} vs. {{ game.away_team }}</p></th>
<th id = "field"><p>{{ game.get_field_display }}</p></th>
<th id = "date"><p>{{ game.date.date }} at {{ game.date.time }}</p></th>
<th id = "score"><p>{{ game.score }}</p></th>
<th id = "result"><p>{{ game.result }}</p></th>
</tr>
{% endfor %}
</tbody>
</table>
Итак, мой вопрос: как я могу это сделать, не отображая лишнюю пустую строку в таблице? Я предполагаю, что это как-то связано с цепочкой itertool, которую я использую в представлении, потому что, когда я просто выполняю простой запрос для Game, этого не происходит.
Я думаю, проблема в том, что вы объединяете два разных набора запросов. Переменные можно отправлять через контекст:
class Season(generic.ListView):
model = SeasonModel
template_name = 'team/season.html'
def get_queryset(self):
return SeasonModel.objects.filter(current=True)
def get_context_data(self,**kwargs):
context = super(Season,self).get_context_data(**kwargs)
context['games_list'] = GameModel.objects.all().order_by('date')
return context
в yout html у вас есть две разные переменные
{% for season in object_list %}
<a href = ""><h5 id = "session">{{ season.year }} {{ season.session }} session</h5></a>
'''
{% endfor %}
для игры у вас games_list
{% for game in games_list %}
<tr>
'''
</tr>
{% endfor %}
Вау, сработало как шарм. Я застрял на этом весь день. Я проголосовал за вас, но не уверен, что я новичок. Спасибо за помощь и за быстрый ответ.
почему вы объединяете два разных набора запросов в один? пусть набор запросов только для SeasonModel, а другой набор запросов отправляется через контекст