Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<function RegisterSerializerStudent.create.<locals>.create_new_ref_number at 0x000001E4C463A950>

>Solution :

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
    
    # …
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading