【发布时间】:2019-03-05 19:29:20
【问题描述】:
我目前正在开发像 IMDB.com 这样的 django 应用程序,它有一个媒体(包含电视节目和电影)模型和一个情节模型,它们之间存在一对多关系,以便在电视节目页面上显示这些情节。
我设法能够在页面内显示电视节目的剧集:
def tvshow(request, tvshow_title):
tvshow = get_object_or_404(Media, title=tvshow_title)
episodes = Episode.objects.all().filter(is_published=True, tvshow=tvshow)
context = {
'tvshow': tvshow,
'episodes': episodes
}
return render(request, 'media/tvshow.html', context)
这工作得非常好,但我还需要根据季节显示剧集,这让我有点困惑,当媒体模型中没有适合它的字段时,我怎么知道电视节目有多少季,但是剧集模型有一个 season_number 字段,所以我尝试根据 season_number 查询电视节目的最后一集:
latest_episode = Episode.objects.order_by('-season_number').filter(is_published=True, tvshow=tvshow)[:1]
我确实设法获得了这一集,但我现在不知道如何获得其中的季节编号。
我试过了
seasons = latest_episode.season_number
和
seasons = latest_episode['season_number']
他们都没有工作。请告诉我是否有更好的方法,如果这种方法很好,请告诉我如何获取 season_number。 :)
【问题讨论】:
-
你能打印
latest_episode并分享结果吗? -
用
.first()代替[:1]。 -
另外,
Episode.objects.all().filter(is_published=True, tvshow=tvshow)中不需要.all()(因为.filter()是多余的
标签: django