Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

414
Vistas
eliminate duplicates in django

I'm trying to pick up 3 random numbers out of a list of 20 numbers.

In views.py, I've defined this variable:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

In my template index.html:

{{ nums|random }} - {{ nums|random }} - {{ nums|random }}

I want to get 3 different numbers, but I don't know which filter/tag to apply.

I've tried if/else statements, for loops, (if there's a duplicate I want a redraw) but i'm not satisfied with the results and I'm pretty sure there's a simple filter to do that.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I don't think there's a reasonable way to do this with the built in filters. I'd just pick the numbers in the view and pass that in to the context.

If your rendering is consistent and you want to do this a lot of places you could write a custom template tag, eg:

import random
from django import template

register = template.Library()

@register.simple_tag
def random_sample(population, k):
    return ' - '.join(str(choice) for choice in random.sample(population, k))

Then {% random_sample nums 3 %} in your template.

But I think doing it in the view is simpler.

over 4 years ago · Santiago Trujillo Denunciar

0

You could create your templatetag with this functionalitiy to solve your problem.

yourapp/templatetags/custom_choice_tags.py

from django import template
import random

register = template.Library()

@register.assignment_tag
def get_three_unique_random_values_from_list(value_list):
    random_choices = random.sample(value_list, 3)
    selected_choices = {
        'first_choice': random_choices[0],
        'second_choice': random_choices[1],
        'third_choice': random_choices[2],
    }
    return selected_choices

and then in your template.html:

{% load custom_choice_tags %}

{% get_three_unique_random_values_from_list random_list  as random_choices %}

 {{ random_choices }} 

the variable random_list would be passed from your view into the template context in this example.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda