Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
How to get only one random element from object?

My model.py is this.

class Country(models.Model):
    country_name = models.CharField(max_length=200)
    country_fact = models.CharField(max_length=1000)
    country_capital = models.CharField(max_length=100)
    country_flags = models.ImageField(upload_to='flags')

View.py is this

def index(request):
    country = Country.objects.all()
    return render(request,'index.html',{'country':country})

I'm retrieving those data in HTML by using this

{% for count in country %}
 <img src="{{ count.country_flags.url }}">

This retrieves all the country images from the database(I'm using Postgresql). I want to retrieve only one random country flag from the database. How can I achieve this? Thanks for the help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

import random

def index(request):

    country = Country.objects.all()
    choosen = random.choice(country)


    context = {
        'country': country,
        'choosen': choosen
    }
    return render(request,'index.html',context)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!