Django 是個便於新人上手的 web 專案,內建簡單的 Django-ORM ,但卻無法很好的對已存在的資料庫進行連結,功能強大的 Sqlalchemy 又不面向新手,故小造輪子,以便的對已存在的表增刪該查,其中查詢語法類似 Django ORM,同時加入了方便的 join 操作。該工具支援批量操作。
功能簡介
假設使用如下語法建立了兩張表: users
和 addresses
CREATE TABLE users (
id INTEGER NOT NULL,
name VARCHAR(50),
fullname VARCHAR(50),
password VARCHAR(12),
PRIMARY KEY (id)
);
CREATE TABLE addresses (
id INTEGER NOT NULL,
email_address VARCHAR NOT NULL,
user_id INTEGER,
PRIMARY KEY (id),
FOREIGN KEY(user_id) REFERENCES users (id)
);
複製程式碼
你可以使用支援的 Database Urls 對已存在於資料庫中的表進行連結並作出相應操作。
from dblink import Database, Table
db = Database(url='sqlite:///:memory:')
user_table = Table('users', db)
# ...
db.close()
with Database(url='postgresql://scott:tiger@localhost/mydatabase') as db:
address_table = Table('addresses', db)
# ...
複製程式碼
下面是一個簡單的操作示例:
"""
Suppose you have two table: users and addresses.
"""
from dblink import Database, Table
with Database('sqlite:///:memory:') as db:
table_user = Table('users', db)
table_address = Table('addresses', db)
# show description
print(table_user.description)
print(table_address.description)
# chain query, you can call delete on the single table result
table_user.query.filter(id=1).one_or_none()
table_user.query.filter(id__gte=2) \
.order_by('name') \
.values_list('id', 'name')
table_user.query.filter(id__in=[1, 2, 3]) \
.filter(name__startswith='Yu').all()
table_user.query.order_by('-name') \
.values_list('fullname', flat=True, distinct=True)
table_user.query.distinct('name').values_list('name', flat=True)
table_user.query.filter(id__in=[1, 2, 3]).delete()
# join query
table_user.join(table_address) \
.filter(id__lt=10000) \
.filter(email_address__contains='gmail') \
.filter(**{'addresses.id__gte': 100}) \
.values_list('user_id', 'name', 'email_address',
table_address.id, 'users.fullname')
# get or insert
instance, create = table_user.get_or_insert(id=1, name='jone')
# single record operation.
table_user.insert({'id': 1, 'name': 'YuJun', 'password': 'psw'})
table_user.update({'id': 1, 'name': 'skyduy', 'password': 'psw'},
unique_fields=['id'], update_fields=['name', 'password'])
table_user.insert_or_update(
{'id': 1, 'name': 'skyduy', 'password': 'psw'},
unique_fields=['id'], update_fields=['name', 'password']
)
table_user.delete({'id': 1, 'name': "I don't matter"},
unique_fields=['id'])
# bulk operation
items = [{'id': 1, 'name': 'yujun', 'password': 'haha'},
{'id': 2, 'name': 'skyduy', 'password': 'aha'},]
unique_fields = ['id']
update_fields = ['name']
table_user.bulk_insert(items)
table_user.bulk_delete(items, unique_fields)
table_user.bulk_update(items, unique_fields, update_fields)
table_user.bulk_insert_or_update(items, unique_fields, update_fields)
複製程式碼
安裝和原始碼
- 直接使用 pip 安裝:
pip install dblink
- 原始碼請戳這裡