【问题标题】:Django: How can I reverse objects with DetailView?Django:如何使用 DetailView 反转对象?
【发布时间】:2018-12-02 08:42:07
【问题描述】:

我使用了通用视图。每一集都通过 ForeignKey 连接到某个季节。在views.py 我有这些:

class SeasonList(generic.ListView):
    template_name = 'episodes/episodes.html'
    context_object_name = 'all_seasons'

    def get_queryset(self):
        return reversed(Season.objects.all())

# Here I need to sort the episodes     
class SeasonDetails(generic.DetailView):
    model = Season
    template_name = 'episodes/season_details.html'   

在列表视图中,我使用 reversed() 首先显示最新一季。同样,在详细视图中,我希望剧集按降序显示,因为最新的剧集应该出现在页面顶部。

在我的 html 中,我使用 season.episode_set.all 访问了剧集列表

    {% for episode in season.episode_set.all %}

       <!-- the tags to show the list -->

    {% endfor %}

有什么办法可以反转剧集列表吗?

【问题讨论】:

    标签: django python-3.x sqlite django-generic-views


    【解决方案1】:

    您可以通过id 订购,并根据您的需要使用后代- 或升序

    
    Season.objects.all().order("id") # Ascendant
    
    Season.objects.all().order("-id") # Decendant
    

    reverse() 可以反转查询集,无论您的过滤器如何。

    Season.objects.all().reverse()
    

    【讨论】:

    • 但它会颠倒季节的对象。我已经做到了。实际上,我正在寻找一种可以扭转情节的方法。我使用外键将剧集与某个季节联系起来。抱歉,如果我未能正确描述我的问题。
    【解决方案2】:

    要对剧集进行排序,您可以使用类似这样的东西 -

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['episodes'] = Episodes.objects.all().order_by('-date_posted')
        return context
    

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2016-06-10
      • 2018-05-31
      • 2021-04-15
      • 2020-08-31
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2015-06-08
      相关资源
      最近更新 更多