Random search doesn’t work

Asked

Viewed 58 times

0

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

My view.py:

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

In 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.

  • I don’t think it’s duplicate @fernandosavio. Pedro failed to give the correct context that is of a Django application and not pure SQL, IE, he is using the ORM for this.

  • You’re right @Andréduarte. I removed the flag, his doubt seems to me more like Queryset than with Andom itself. Thank you!

2 answers

1


Tendencias 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]

0

Good morning, Buddy, depending on the database you’re using, you can put a clasp on WHERE, which throws the random in the column id, and give a TOP 1 (Sql server), Limit 0, 1 (postgres, mysql). Thus, it will always catch a random ID value, and as it is in TOP 1, it will catch the first occurrence. I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.