You can download this code by clicking the button below.
This code is now available for download.
This function creates a random user document using PyMongoEngine's Document and EmbeddedDocument classes to define user information and user profile.
Technology Stack : PyMongoEngine
Code Type : PyMongoEngine Document
Code Difficulty : Intermediate
from mongoengine import Document, StringField, BooleanField, EmbeddedDocument, ListField
from random import choice
def create_random_user_document():
# Define a simple user document
class User(Document):
username = StringField()
email = StringField()
is_active = BooleanField(default=True)
profile = EmbeddedDocumentField('Profile')
# Define a simple profile document
class Profile(EmbeddedDocument):
bio = StringField()
age = StringField()
location = StringField()
# Create a random user document
user = User(
username=choice(['JohnDoe', 'JaneDoe', 'Alice', 'Bob']),
email=choice(['johndoe@example.com', 'janedoe@example.com', 'alice@example.com', 'bob@example.com']),
profile=Profile(
bio=choice(['I love programming', 'I enjoy hiking', 'I am a musician', 'I like reading']),
age=choice(['25', '30', '35', '40']),
location=choice(['New York', 'London', 'Paris', 'Berlin'])
)
)
# Save the document to the database
user.save()