You can download this code by clicking the button below.
This code is now available for download.
This function creates a random Person object and saves it to the database. The Person object has name and age properties, which are randomly generated.
Technology Stack : Peewee, SQLite
Code Type : Function
Code Difficulty : Intermediate
import random
from peewee import *
# Create a database instance
db = SqliteDatabase('my_database.db')
# Define a model
class Person(Model):
name = CharField()
age = IntegerField()
class Meta:
database = db
def create_random_person():
"""
This function creates a random person and saves it to the database.
"""
# Create a new person instance
person = Person(name=f'Person{random.randint(1, 100)}', age=random.randint(18, 70))
# Save the person to the database
person.save()
# Create the database and tables
db.connect()
db.create_tables([Person])
# Example usage
create_random_person()
# Close the database connection
db.close()