我正在尝试过滤数据库中的对象列表,但我无法使用_set.all
让它在模板上工作。奇怪的是,这是我在我的项目中的其他两个地方所做的事情,但我不知道为什么这次不工作。
view.py:
class GolfMonthlyView(generic.ListView):
template_name="monthly_view/golf-monthly-view.html"
context_object_name='golf_monthly_view'
queryset = GolfMonthlyView.objects.all()
def get_context_data(self, **kwargs):
context = super(GolfMonthlyView, self).get_context_data(**kwargs)
context['golftour'] = golf_models.Tour.objects.all()
context['golftournament'] = golf_models.Tournament.objects.all()
模型:
class Tour(models.Model):
name = models.CharField(max_length=100)
class Tournament(models.Model):
tour = models.ForeignKey('Tour', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
模板html:
{% for info in golf_monthly_view %}
{% for competition in golftour %}
{% for golftournament in golftour.golftournament_set.all %}
<ul>
<li>{{golftournament.name}}</li>
</ul>
{% endfor %}
{% endfor %}
{% endfor %}
所有这一切的好消息是试图解决我的问题,迫使我第一次正确使用Django Shell。所以我知道关系是有效的,它只是在模板中显示。
编辑:工作:
class RugbyMonthlyView(generic.ListView):
template_name="monthly_view/rugby-monthly-view.html"
context_object_name='rugby_monthly_view'
queryset = RugbyMonthlyView.objects.all()
def get_context_data(self, **kwargs):
context = super(RugbyMonthlyView, self).get_context_data(**kwargs)
context['competition'] = rugby_models.Competition.objects.all()
context['match'] = rugby_models.Match.objects.all()
return context
model.py:
class Competition(models.Model):
name = models.CharField(max_length=200)
class Match(models.Model):
competition = models.ForeignKey('Competition', on_delete=models.CASCADE)
html模板:
{% for match_info in rugby_monthly_view %}
{% for competition in competition %}
*code*
{% for match in competition.match_set.all %}
*code*
{% endfor %}
{% endfor %}
{% endfor %}
答案 0 :(得分:1)
你有golftour.golftournament_set.all
嵌套在上下文列表golf_monthly_view
的循环中(不知道你为什么要这样做),我认为这是空的,因为ListView QuerySet是错的:
queryset = GolfMonthlyView.objects.all()
# ^^^^ ?? This is not a model
例如,如果您从外部中取出循环,则如果QuerySets不为空,则内部循环应该继续:
{% for competition in golftour %}
{% for golftournament in golftour.tournament_set.all %}
<ul>
<li>{{golftournament.name}}</li>
</ul>
{% endfor %}
{% endfor %}