Django如何排序对象有外键关系?



在我的Django应用程序中,我想显示一些TV-Show条目。目前,我想建立一个过滤器的电视节目有最新发布的剧集排序。但我不确定这个问题应该是什么样的。这是我如何提取过去90天的剧集

def tv_show_by_set_just_released(request):
latest_episodes = TvShowEpisodes.objects.filter(
release_date__lte=datetime.datetime.today(),
release_date__gt=datetime.datetime.today()-datetime.timedelta(days=90)).order_by('-release_date')

但是我现在怎么能引用这一集的实际电视节目呢?我想按最新添加的剧集(release_date)对电视节目进行排序请看看我的造型:

class TvShows(models.Model):
objects = RandomManager()
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255)
genre_relation = models.ManyToManyField(through='GenreTvShow', to='Genre')
date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added"))

class TvShowEpisodes(models.Model):
objects = RandomManager()
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
duration = models.FloatField(verbose_name=_("Duration"), blank=True, null=True, editable=False, max_length=255)
title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255)
release_date = models.DateField(verbose_name=_("Release Date"), blank=True, null=True, editable=False)
track = models.IntegerField(verbose_name=_("Track #"), blank=True, null=True)
show = models.ForeignKey(TvShows, on_delete=models.CASCADE, related_name='episode_show_relation')
season = models.ForeignKey(TvShowSeasons, on_delete=models.CASCADE, related_name='episode_season_relation')
episode_id = models.CharField(verbose_name=_("Episode ID"), max_length=255, blank=True, null=True, editable=False)
episode_sort = models.IntegerField(verbose_name=_("Episode Number"), blank=True, null=True, editable=False)
synopsis = models.TextField(verbose_name=_("Synopsis"), blank=True, null=True, editable=False, max_length=255)
date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added"))

可以通过以下方式检索TvShows:

from django.db.models import Max
TvShows.objects.alias(
latest_episode_release=Max('episode_show_relation__release_date')
).order_by('-latest_episode_release')

或django-3.2之前版本:

from django.db.models import Max
TvShows.objects.annotate(
latest_episode_release=Max('episode_show_relation__release_date')
).order_by('-latest_episode_release')

相关内容

  • 没有找到相关文章

最新更新