Home > Back-end >  Django Drf: generate an 8 digit unique number in the user serializer
Django Drf: generate an 8 digit unique number in the user serializer

Time:12-16

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>

CodePudding user response:

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
    
    # …
  • Related