Python and databases: SQLAlchemy, Django ORM

In this article, we'll explore how to use SQLAlchemy and Django ORM in Python to interact with databases. We will detail the rationale for these libraries and show through code examples how to apply them to real projects.

1. Introduction to the database

A database is a key component for storing and managing data. The Python community provides many libraries for database manipulation, of which SQLAlchemy and Django ORM are two of the most popular. We will explore the usage of these two libraries in depth in this article.

2. SQLAlchemy

2.1. Introduction to SQLAlchemy

SQLAlchemy is a powerful Python library for working with relational databases. It provides SQL expression language and ORM (Object Relational Mapping) to realize the interaction with the database.

2.2. Basic usage of SQLAlchemy

To use SQLAlchemy you first need to install this library:

pip install sqlalchemy

Next, we'll create a simple database model:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///example.db')
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

Base.metadata.create_all(engine)

2.3. Example: Using SQLAlchemy to implement CRUD operations

The following is a simple example of adding, deleting, modifying and querying using SQLAlchemy:

# 添加数据
Session = sessionmaker(bind=engine)
session = Session()

user = User(name='John Doe', age=30)
session.add(user)
session.commit()

# 查询数据
users = session.query(User).all()
for user in users:
    print(user.name, user.age)

# 更新数据
user = session.query(User).filter_by(name='John Doe').first()
user.age = 35
session.commit()

# 删除数据
user = session.query(User).filter_by(name='John Doe').first()
session.delete(user)
session.commit()

session.close()

3. Django ORM

3.1. Introduction to Django ORM

Django is a popular Python web framework, and its ORM (object-relational mapping) component allows developers to use Python classes and objects to interact with databases without writing SQL code.

3.2. Basic usage of Django ORM

To use Django ORM, you first need to install Django:

pip install django

Create a new Django project and application:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

Next, myapp/models.pycreate a database model in the file:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

    def __str__(self):
        return self.name

3.3. Example: Using Django ORM to implement CRUD operations

The following is a simple example of using Django ORM to implement CRUD operations:

# 添加数据
user = User(name='John Doe', age=30)
user.save()

# 查询数据
users = User.objects.all()
for user in users:
    print(user.name, user.age)

# 更新数据
user = User.objects.filter(name='John Doe').first()
user.age = 35
user.save()

# 删除数据
user = User.objects.filter(name='John Doe').first()
user.delete()

4. Summary

In this article, we discussed in detail how to interact with databases using SQLAlchemy and Django ORM in Python. Through the code examples in this article, you can gain a deeper understanding of the usage of these two libraries and apply them to real projects.

5. References

[1] SQLAlchemy official documentation: https://docs.sqlalchemy.org/en/14/

[2] Django official documentation: https://docs.djangoproject.com/en/4.1/

Guess you like

Origin blog.csdn.net/qq_33578950/article/details/130110610