SQLAlchemy 使用 二 表關聯

2022-01-23 03:23:35 字數 2345 閱讀 9255

在上一章中我們介紹了 sqlalchemy 建立基本表,但是一般情況下,表之間是有關聯的,比如 一對一/一對多/多對多,當然 sqlalchemy 是支援建立model時指定關係的

我們建立兩個表,vip和vip_info, 邏輯應該是一對一,我們先測試一對多

class

vip(base):

# vip使用者

__tablename__ = 'vip

'# 表名

id = column(integer, primary_key=true) # id

name = column(string(12), nullable=false, index=true, unique=true) # name

pwd = column(string(25), nullable=false) # pwd

money = column(integer, nullable=true) # 金幣

status = column(integer, nullable=false) # 賬號狀態(1:正常,0:封禁,2

:審核)

class

vipinfo(base):

# vip資訊

__tablename__ = 'vip

_info

'# 表名

id = column(integer, primary_key=true) # id

info = column(string(256

)) # 備註

fk_vip_info_on_vip = column(integer, foreignkey('vip

.id'

)) # 關聯外來鍵vip.id(多對一)(這裡的vip是tablename不是class名)

vip = relationship('

vip', backref=backref('

vip_info

')) # 設定關聯使vipinfo能查詢到vip, 注意這裡的欄位名在序列化元件的跨表時有用

注意,設定多對一的時候,只設定foreignkey只能從 vip 查詢到 vipinfo,必須要設定 relationship 才可以反向查詢(從vip查詢到vipinfo)

一對一與多對一差不多,如果想要一對一,只需要在原有 多對一 的 多 字段設定 unique(唯一)即可

我們把之前的**改成一對一

class

vip(base):

# vip使用者

__tablename__ = 'vip

'# 表名

id = column(integer, primary_key=true) # id

name = column(string(12), nullable=false, index=true, unique=true) # name

pwd = column(string(25), nullable=false) # pwd

money = column(integer, nullable=true) # 金幣

status = column(integer, nullable=false) # 賬號狀態(1:正常,0:封禁,2

:審核)

class

vipinfo(base):

# vip資訊

__tablename__ = 'vip

_info

'# 表名

id = column(integer, primary_key=true) # id

info = column(string(256

)) # 備註

fk_vip_info_on_vip = column(integer, foreignkey('vip

.id'), unique=true, index=true) # 關聯外來鍵vip.id(多對一)

vip = relationship('

vip', backref=backref('

vip_info

', uselist=false)) # 設定關聯使vipinfo能查詢到vip, 注意這裡的欄位名在序列化元件的跨表時有用

需要值得注意的是 relationship 多了 uselist=false

這個引數是控制查詢範圍的,如果是一對一我們常把 uselist 設為 false

預設是 true 的, 舉個例子,當我們從 vip表關聯到 vipinfo表時,如果 uselist為true,那麼他會找到對應關聯的所有vipinfo 反之指找乙個就結束.所以一對一時我們直接寫 false 因為我們知道只有乙個對應

第三章我們會介紹如何在 flask中使用 sqlalchemy

使用SQLAlchemy來構建表

from datetime import datetime from flask sqlalchemy import sqlalchemy from sqlalchemy.dialects.mysql import tinyint,bigint,varchar,char,datetime,integ...

使用sqlalchemy建表並從txt檔案讀取入庫

首先資料庫要存在,我使用的是mysql資料庫。from sqlalchemy import column,string,create engine,integer from sqlalchemy.orm import sessionmaker,scoped session from sqlalche...

SQLAlchemy基礎操作二

usr bin env python coding utf 8 import time import threading from sqlalchemy.ext.declarative import declarative base from sqlalchemy import column,int...