Problem with separating images using Django

hi I am loading images using Django but I want to sperate images which end with jpg and png , how do I do that ? thank you .

 {% if obj.image.url|slice:"-4:" == ".jpg" %}

    <img class="img-fluid" style="border-radius: 5px;max-width: 100%;
    max-height: 100%;
    display: block;" width="100%" data-src="{{  obj.image.url  }}" alt="Image ">
{% endif %}

found the answer

You can use the filter() method on the queryset of images and check for the file extension using the endswith() method on the attribute. Here's an example:

  from django.db.models import Q

  jpg_images = MyModel.objects.filter(image_field__endswith='jpg')
  png_images = MyModel.objects.filter(image_field__endswith='png')

This will give you two querysets, one for jpg images and another for png images.

You can also use 'OR' operator and filter both extensions in one go

    images = MyModel.objects.filter(Q(image_field__endswith='jpg') | Q(image_field__endswith='png'))

This will give you a queryset of images that end with both jpg and png.

Back to Top