Home > Software engineering >  Django - How to get image field of ForeignKey query elements?
Django - How to get image field of ForeignKey query elements?

Time:09-24

I have the following code at views.py to sort TvShows by there latest released episode (release_date) within 90 days:

def tv_show_by_set_just_released(request):
    latest_episodes = TvShows.objects.filter(episode_show_relation__release_date__gte=now() - datetime.timedelta(days=90))
...

For each element found, I now also want to display a cover. But the cover is located at a different table and I don't really know how to pull it out probably in this query context. In the end I want to display the very first TvShowSeasons.cover for each element of my query from above. Is it somehow possible to marry these two elements, latest_episodes and TvShowSeasons.cover to display them properly at a template?

Please also see models.py

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 TvShowSeasons(models.Model):
    objects = RandomManager()
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    show = models.ForeignKey(TvShows, on_delete=models.CASCADE, related_name='season_show_relation')
    season_number = models.IntegerField(verbose_name=_("Season Number"), blank=True, null=True, editable=False)
    cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images)
    cover_tn = models.ImageField(verbose_name=_("Cover Thumbnail"), blank=True, null=True, upload_to=get_file_path_images)
    total_tracks = models.IntegerField(verbose_name=_("Total Tracks #"), blank=True, null=True)
    rating = models.CharField(verbose_name=_("Rating"), blank=True, null=True, editable=False, max_length=255)
    copyright = models.TextField(verbose_name=_("Copyright"), blank=True, null=True, editable=False, max_length=255)
    date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added"))

Thanks in advance

CodePudding user response:

That is what related_name argument in ForeignKey is meant to be. Assuming you return latest_episodes as context, here is how you can access cover for each episode in templates:

{% for episode in latest_episodes %}
    <p>Episode name: {{ episode.title }}</p>
    <img src="{{ episode.season_show_relation.first.cover.url }}">
{% endfor %}
  • Related