Detailed explanation of Pony ORM, the ORM framework in Python

WBOY
Release: 2023-06-10 21:30:34
Original
2652 people have browsed it

Python is a high-level programming language that is widely used in web development, scientific computing, data processing and other fields. In Python development, the ORM (Object-Relational Mapping) framework is an important component. It can establish a coherent bridge between relational databases and object-oriented programming languages, and facilitate the development work of Python programmers.

Among many Python ORM frameworks, Pony ORM is a lightweight object-relational mapping tool. It uses the natural and simple syntax of the Python language and provides rich functions that can quickly map Python objects to Implement persistence in relational databases.

  1. Installation

First, we need to install it through the pip package management tool.

pip install pony

  1. Quick Start

2.1 Connect to the database

First, we need to connect to a database. Pony ORM supports multiple A relational database, including MySQL, PostgreSQL, SQLite, Oracle, MS SQL Server, etc. Let's take SQLite as an example.

from pony.orm import *

db = Database()

db.bind(provider='sqlite', filename='database.sqlite', create_db=True )

Note that before connecting to the database, you need to define a Database instance, and then specify the database type and database name through the bind() method. If the database does not exist, you can use the create_db=True option to automatically create the database.

2.2 Define entity class

Next, we need to define a Python class and convert it into an entity class through the db.Entity() decorator. Attributes in an entity class are mapped to table columns in the database, and instances of the entity class correspond to rows in the table.

class Customer(db.Entity):

name = Required(str)
age = Required(int)
address = Optional(str)
Copy after login

In the above code, we define a Customer entity class and three attributes: name, age and address. Among them, name and age are required attributes (Required), and address is an optional attribute (Optional).

2.3 Create a table

After creating the entity class, we need to create the corresponding table structure in the database. This can be done through the db.generate_mapping() method.

db.generate_mapping(create_tables=True)

After the above steps, we have successfully connected to the database, defined an entity class, and created the corresponding table in the database.

  1. Create, Delete, Modify and Check

3.1 Inserting data

Inserting data is a common operation. Through Pony ORM, we can easily insert data.

with db_session:

c1 = Customer(name='Tom', age=20)
c2 = Customer(name='Jerry', age=25, address='New York')
flush()
Copy after login

In the above code, we use the with db_session keyword to declare a session, and then create two Customer instances c1 and c2 by instantiating the Customer entity class, and Assign it to a variable. Next, we call the flush() method to insert instances c1 and c2 into the database.

3.2 Querying data

Querying data is one of the most commonly used functions of the ORM framework. Through Pony ORM, we can use query expressions or ORM objects to query data.

Query expression:

select(c for c in Customer if c.age > 20)

In the above code, we use the select() function to specify the The entity class to be queried. Here we specify to query the records in the Customer table that are older than 20 years old. Finally, we use the with db_session context containing the select() function to perform the query operation.

ORM object:

with db_session:

customers = Customer.select(lambda c:c.age > 20)
for c in customers:
    print(c.name, c.age, c.address)
Copy after login

In the above code, we use the with db_session keyword to declare a session and use Customer.select() to query the Customer table Records in which the age group is over 20 years old. Query results are represented as ORM objects, and we can access their properties and methods just like Python objects. Finally, we use a for loop to output the query results.

3.3 Update data

The operation of updating data is very simple. We only need to query the records that need to be updated first, then modify the corresponding attribute values, and finally call the flush() method to save the modified data. That’s it.

with db_session:

customer = Customer.get(name='Tom')
customer.address = 'Beijing'
flush()
Copy after login

In the above code, we use the Customer.get() statement to query the customer record named Tom, and then modify its address to Beijing. Finally, we save the updated data to the database by calling the flush() method.

3.4 Deleting data

Deleting data is also very simple. We only need to query the record that needs to be deleted first, and then call its delete() method.

with db_session:

customer = Customer.get(name='Tom')
customer.delete()
Copy after login

In the above code, we use the Customer.get() statement to query the customer record named Tom, and then call its delete() method to delete the customer record from the database. Record.

  1. Summary

Pony ORM is a simple, easy-to-use, feature-rich Python ORM framework that can quickly map Python objects to relational databases for persistence. change. When using Pony ORM, we need to first connect to the database, then define entity classes, create tables, and finally implement operations such as addition, deletion, modification, and query through query expressions or ORM objects. For beginners, Pony ORM is a very friendly ORM framework with low learning costs, allowing you to get started quickly.

The above is the detailed content of Detailed explanation of Pony ORM, the ORM framework in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template