1👍
✅
You can use a custom Manager
and QuerySet
, like this:
class PhotoQuerySet(models.query.QuerySet):
def frontpage_thumb(self):
return self.filter(frontpage_thumb=True)
class PhotoManager(models.Manager):
use_for_related_fields = True
def get_queryset(self):
return PhotoQuerySet(self.model)
class Photo(models.Model):
# ...
objects = PhotoManager()
Then you can do things like:
# get first thumb for a gallery:
>>> g = Gallery.objects.all()[0]
>>> thumb = g.photo_set.all().frontpage_thumb()[0]
# or all thumbs for all galleries:
>>> all_thumbs = Photo.objects.all().frontpage_thumb()
Because your schema doesn’t guarantee that you only have one Photo
per Gallery
with frontpage_thumb=True
set, you still have to get the first element of the result in the template, using .0
, like in the first Python example above:
{% for gallery in gallery_list %}
<img src="{{ gallery.photo_set.all.frontpage_thumb.0.image.url }}">
{% endfor %}
👤sk1p
Source:stackexchange.com