[Answered ]-Django Drf: generate an 8 digit unique number in the user serializer

1👍

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

Leave a comment