0

I would like to ask, if it is possible to pick existing random object id in template.

Here are my models.py:

class ImageInGallery(models.Model):
      image = models.ImageField(upload_to='media/photos/')

views.py;

class GalleryListView(ListView):
     model = ImageInGallery
     context_object_name = 'images'

     def get_queryset(self):
         return ImageInGallery.objects.all().order_by('-id')

In the template I would like to to something like this:

{% for picture in images %}
   {% if picture.id == X %}
      <img src="{{ picture.image.url }}">
   {% endif %}
{% endfor %}

Where 'X' is the existing random object id of the image model. Is there any way how to do it? Or is there any other better way? Thank you.

pipikej
  • 185
  • 10
  • What do you mean by random number? Is it a number specified you or a number randomly generated by the template? – Swetank Poddar May 21 '20 at 19:55
  • Did you try to just randomly provide an object? ImageInGallery.objects.order_by("?").first() – S.D. May 21 '20 at 19:59
  • @SwetankPoddar What I mean by a random number is, a random existing object. I want to have on the web site 10 random pictures on the website and if you hit refresh they all change randomly. – pipikej May 21 '20 at 20:03
  • @S.D. Well that would work if I would like only to display one image, but I want to display 10 of them. – pipikej May 21 '20 at 20:03
  • 1
    You can grab the first 10 by slicing: ImageInGallery.objects.order_by("?")[0:10] – S.D. May 21 '20 at 20:08
  • @SwetankPoddar Well, not exactly, but at least something :) – pipikej May 21 '20 at 20:14
  • what about something like: `random.choice(ImageInGallery.objects.all().order_by('-id'), k=10)` (in your view) as your number of required elements is less... this should be okay – Swetank Poddar May 21 '20 at 20:21
  • I like the accepted answer to this question: https://stackoverflow.com/questions/25961092/django-random-orderingorder-by-makes-additional-query -- pull your records into a list in a single query and use Python's `shuffle` to randomize. But, the best solution for you will depend on the size of your database, what database you are using, etc, etc... – Jim May 21 '20 at 20:28

0 Answers0