Random search does not work

0

I want to do a random search in the database, but it is not working. I want to take a sentence, and show it on the screen, it will be changed every time I refresh the screen.

My view.py:

def busca_tendencia(request):
    tendencias = Frase.objects.all().order_by('?')
    return render(request, 'busca/index.html', {'tendencias': tendencias})

No html:

{{ tendencias.frase }}

My models.py

class Frase(models.Model):
    titulo = models.CharField(max_length=300, blank=False)
    frase = models.TextField()
    data = models.DateTimeField(default=timezone.now)

    class Meta:
        verbose_name  = 'Frase'
        verbose_name_plural = 'Frases'

When accessing the page does not return anything, nor error. And the phrase does not appear.

    
asked by anonymous 25.10.2018 / 14:50

2 answers

1

Trends is returning all objects or bank lines

Do so

from random import randint
...
tendencias = Frase.objects.all().order_by('?').first()
#ou entao assim para pegar um registro realmente aleatorio
tendencias = Frase.objects.all().order_by('?')
registro_aleatorio = randint(1, tendencias.count())
tendencia = tendencias[registro_aleatorio]
    
25.10.2018 / 16:08
0

Good morning, Friend, depending on the database you are using, you can put a clause in the WHERE , which plays the random in the column id, and give a TOP 1 (Sql server ), Limit 0, 1 (postgres, mysql). So it will always get a random ID value, and as it is in TOP 1, it will get the first occurrence. I hope I have helped.

    
25.10.2018 / 15:36