django

11 views
Skip to first unread message

Jonathan Bilesi

unread,
Mar 29, 2021, 4:17:58 PM3/29/21
to Django users
hi 
i getting this error 
ValueError at /empty range for randrange() (0, 0, 0)

here my code 

    random_object = Trending.objects.all()[randint(0, len(trending) -1)] 

Fabio C. Barrionuevo da Luz

unread,
Mar 29, 2021, 4:39:46 PM3/29/21
to django...@googlegroups.com
Your implementation can probably be changed to something like this



import random

all_qs = Trending.objects.all()
if all_qs.exists(): # checks whether to return at least one record
# query all pk numbers and convert to a tuple
all_pks = tuple(all_qs.values_list("pk", flat=True))
# get a random pk number from the tuple
random_pk = random.choice(all_pks)
# get a object by the random pk
random_object = Trending.objects.get(pk=random_pk)


ps: I have not tested this code.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/61600bb6-f877-4588-a799-0b29109d43d5n%40googlegroups.com.


--
Fábio C. Barrionuevo da Luz
Palmas - Tocantins - Brasil - América do Sul


Blog colaborativo sobre Python e tecnologias Relacionadas, mantido totalmente no https://github.com/pythonclub/pythonclub.github.io .

Todos são livres para publicar. É só fazer fork, escrever sua postagem e mandar o pull-request. Leia mais sobre como publicar em README.md e contributing.md.
Regra básica de postagem:
"Você" acha interessante? É útil para "você"? Pode ser utilizado com Python ou é útil para quem usa Python? Está esperando o que? Publica logo, que estou louco para ler...

Reply all
Reply to author
Forward
0 new messages