Django ORM User Creation and Data Retrieval

  • Share this:

Code introduction


This function uses Django's ORM system to create a new user and return their data.


Technology Stack : Django, Django ORM, Django User Model

Code Type : Django ORM operation

Code Difficulty : Intermediate


                
                    
import random

def randomize_user_data(arg1, arg2, arg3):
    # Importing Django ORM models and random module from Django
    from django.contrib.auth import get_user_model
    from random import randint

    # Getting the User model from Django's authentication system
    User = get_user_model()

    # Generating random data for a new user
    username = f"user{randint(1000, 9999)}"
    email = f"{username}@example.com"
    password = 'randompassword123'

    # Creating a new user object and saving it to the database
    new_user = User.objects.create_user(username=username, email=email, password=password)

    # Returning the newly created user's data
    return {
        "username": new_user.username,
        "email": new_user.email,
        "id": new_user.id
    }