Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

354
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda