O
O
orange_ov2020-05-30 17:00:51
Django
orange_ov, 2020-05-30 17:00:51

How to select a random record from a database in Django and output the result to a template?

There is models.py :

class Questions(models.Model):
  question = models.CharField('Вопрос',max_length=200)
  q_category = models.CharField('Тема',max_length=200)

  class Meta:
    verbose_name = "Вопрос"
    verbose_name_plural = "Вопросы"

  def __str__(self):
    return self.question

There is views.py :
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
  return render(request, 'cards/index.html', {})


There is index.html:
{% extends 'base.html' %}

{% block content %}
<div>
    <h1>Генератор рандомных вопросов</h1>
    <p>Тема вопроса:</p> # выбрать q_category из models.py
    <button>Получить вопрос</button>
</div>

{% endblock %}


The logic is this: by going to index.html, the user selects a question (q_category) in the "Question topic" selector and receives a random question (question) from models.py.
Questions in the database already exist.

I can't quite figure out how to do this, I guess that this is probably a form with a 'POST' method.
Also, would the objects.order_by('?') method fit here? About 300 questions, won't the method be slow?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-05-30
@bacon

Well, do order_by('?') and measure whether such timings suit you or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question