Home  >  Q&A  >  body text

python - How to get random data every time django calls a tag

The code for

views is like this
kwargs["Random Paragraph"] = Content.objects.order_by("?")[0].content

Is to randomly extract a paragraph each time
Then the index is like this

{{ 随机段落 }}
{{ 随机段落 }}
{{ 随机段落 }}

My purpose is to do this every time I call it
Random paragraph 1 Random paragraph 2 Random paragraph 3

To put it simply, every time the random paragraph tag is called, go to the database to extract the data

大家讲道理大家讲道理2712 days ago739

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-05-18 10:54:56

    I don’t know if I understand your question.

    According to my understanding, you need:

    # view
    # 取出多个随机元素
    # 元素个数不足什么的请自己注意处理
    kwargs["paragraphs"] = Content.objects.order_by("?")[:3].content
    {# 模版 #}
    {# 在循环过程中分别渲染各个“随机段落” #}
    {% for paragraph in paragraphs %}
        {{ paragraph }}
    {% endfor %}

    reply
    0
  • PHPz

    PHPz2017-05-18 10:54:56

    Write a random function

    reply
    0
  • PHP中文网

    PHP中文网2017-05-18 10:54:56

    kwargs["随机段落"] = lambda: Content.objects.order_by("?")[0].content

    reply
    0
  • Cancelreply