【问题标题】:How to get only one random element from object? [duplicate]如何从对象中只获取一个随机元素? [复制]
【发布时间】:2022-02-05 14:55:21
【问题描述】:

我的model.py是这个。

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 是这个

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

我正在使用这个在 HTML 中检索这些数据

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

这将从数据库中检索所有国家/地区图像(我使用的是 Postgresql)。我只想从数据库中检索一个随机的国家标志。我怎样才能做到这一点?感谢您的帮助。

【问题讨论】:

  • 你可以使用import randomrandom.choice(list)

标签: javascript python html django


【解决方案1】:
import random

def index(request):

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


    context = {
        'country': country,
        'choosen': choosen
    }
    return render(request,'index.html',context)

【讨论】:

    猜你喜欢
    • 2013-01-13
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多