[Django]-Django for loop counter break

86👍

Use:

{% for photos in gallery.photo_set|slice:":3" %}

1👍

This is better done in the gallery.photo_set collection. The hard-coded “3” in the template is a bad idea in the long run.

class Gallery( object ):
   def photo_subset( self ):
       return Photo.objects.filter( gallery_id = self.id )[:3]

In your view function, you can do things like pick 3 random photos, or the 3 most recent photos.

   def photo_recent( self ):
       return Photo.objects.filter( gallery_id = self.id ).orderby( someDate )[:3]

   def photo_random( self ):
       pix = Photo.objects.filter( gallery_id = self.id ).all()
       random.shuffle(pix)
       return pix[:3]
👤S.Lott

Leave a comment