Django公司_全部设置过滤器在温度下不工作

2024-06-25 22:41:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图筛选数据库中的对象列表,但无法使用_set.all使其在模板上工作。奇怪的是,这是我在我的项目中在另外两个地方做的事情,但我不明白为什么这次它不起作用。在

视图.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()

型号:

^{pr2}$

模板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

模型.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 %}

Tags: nameinview模板forobjectsmodelscontext
1条回答
网友
1楼 · 发布于 2024-06-25 22:41:14

您将golftour.golftournament_set.all嵌套在上下文列表golf_monthly_view上的一个循环中(不确定为什么要这样做),我认为它是空的,因为ListView查询集是错误的:

queryset = GolfMonthlyView.objects.all()
#          ^^^^ ?? This is not a model

例如,如果您为取消外部循环,则如果查询集不为空,则内部循环应继续:

^{pr2}$

相关问题 更多 >