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

343
Vistas
Django Drf: generate an 8 digit unique number in the user serializer

I have a field in my users model that will only be utilized for a Certain type of user

student_id = models.CharField(_("student id"), validators=[
    MinValueValidator(10_000_000_000),
    MaxValueValidator(99_999_999_999)
],unique=True, max_length=8, blank=True, null=True)

when creating a user in the serializers.py file i tried the below code but didn't work

def create(self, validated_data):
    def create_new_ref_number():
        not_unique = True
        while not_unique:
            unique_id = randint(10000000, 99999999)
            if not User.objects.filter(student_id=unique_id):
                not_unique = False
    instance = User.objects.create(
        student_id=create_new_ref_number,
        firstname=validated_data['firstname'],
        middlename=validated_data['middlename'],
        lastname=validated_data['lastname'],
        age=validated_data['age'],
        phone=validated_data['phone'],
    )

after saving the user the student_id field is populated with the following string

<function RegisterSerializerStudent.create.<locals>.create_new_ref_number at 0x000001E4C463A950>
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You need to call the function:

instance = User.objects.create(
    #             call the function ↓↓
    student_id=create_new_ref_number(),
    # …
)

otherwise it will call str(…) on the function object, and in that case you indeed get a string that presents the name of the function together with the location in memory.

Your function should also return the generated key, so:

def create(self, validated_data):
    def create_new_ref_number():
        unique_id = randint(10000000, 99999999)
        while User.objects.filter(student_id=unique_id):
            unique_id = randint(10000000, 99999999)
        return unique_id
    
    # …
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