sqlite Django:如何使用DetailView反转对象?

zengzsys  于 2023-08-06  发布在  SQLite
关注(0)|答案(2)|浏览(102)

我使用了通用视图。每一集都通过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 %}


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

zf2sa74q

zf2sa74q1#

您可以按id排序,并根据需要使用后代-或升序

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

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

字符串
或者reverse()可以反转查询集,不管你的过滤器是什么。

Season.objects.all().reverse()

2cmtqfgy

2cmtqfgy2#

要对事件进行排序,您可以使用类似于以下内容的内容-

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

字符串

相关问题