sqlalchemy外键的一些东西

数据库:

联表查询:

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

engine = create_engine("mysql+pymysql://root:[email protected]/mysqltest")
Base = declarative_base()

class Student(Base):
    __tablename__ = ‘student‘
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    sex = Column(String(32))
    def __repr__(self):
        return "%s,%s,%s" %(self.id, self.name, self.sex)

class Study_record(Base):
    __tablename__ = ‘study_record‘
    id = Column(Integer, primary_key=True)
    day = Column(Integer)
    status = Column(String(32))
    stu_id = Column(Integer)
    def __repr__(self):
        return "%s,%s,%s" %(self.day, self.status, self.stu_id)

Session_class = sessionmaker(bind=engine)
session = Session_class()

# select a.*,b.* from a,b where a.id=b.s_id
result = session.query(Student, Study_record).filter(Student.id==Study_record.stu_id).all()
print(result)  # [(1,alex,男, 1,YES,1), (1,alex,男, 2,NO,1), (2,jack,男, 1,YES,2), (2,jack,男, 2,YES,2)]
# 此处报错!!有外键关联的时候才能用,而且外键也需要用类映射出来。真TM麻烦!
result1 = session.query(Student).join(Study_record).all()
print(result1)

外键关联之双向反查:

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

engine = create_engine("mysql+pymysql://root:[email protected]/mysqltest")
Base = declarative_base()

#   学员表student跟考勤表study_record是一对多的关系
class Student(Base):
    __tablename__ = ‘student‘
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    sex = Column(String(32))
    def __repr__(self):
        return "%s,%s,%s" %(self.id, self.name, self.sex)

class Study_record(Base):
    __tablename__ = ‘study_record‘
    id = Column(Integer, primary_key=True)
    day = Column(Integer)
    status = Column(String(32))
    stu_id = Column(Integer, ForeignKey(‘student.id‘))
    # 双向反查关系,通过student字段可以看记录对应的学生,反过来通过my_study_record可看学生对应的记录
    student = relationship("Student", backref="my_study_record")
    def __repr__(self):   # self.student.name  这是它的牛逼之处:
        return "%s,%s,%s" %(self.day, self.status, self.student.name)

Session_class = sessionmaker(bind=engine)
session = Session_class()

# 上面加了外键关联,可以用了
result1 = session.query(Student).join(Study_record, isouter=True).all()
print(result1)  # [1,alex,男, 2,jack,男, 3,rose,女]

alex = session.query(Student).filter(Student.name == ‘alex‘).first()
print(alex)  # 1,alex,男
# 如果想查Alex的上课记录咋查呢?在上面加一个双向反查关系
print(alex.my_study_record)  # [1,YES,alex, 2,NO,alex]

顾客表有两个外键,两个外键指向同一张表,此时的双向查询:

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

engine = create_engine("mysql+pymysql://root:[email protected]/mysqltest")
Base = declarative_base()

# 顾客表Customer有两个外键,订单地址ID,邮寄地址ID。都关联了同一张表
class Customer(Base):
    __tablename__ = ‘customer‘
    id = Column(Integer, primary_key=True)
    name = Column(String(32))

    bill_addr_id = Column(Integer, ForeignKey("address.id"))
    post_addr_id = Column(Integer, ForeignKey("address.id"))

    bill_addr = relationship("Address", foreign_keys=[bill_addr_id], backref="bill_customers")
    post_addr = relationship("Address", foreign_keys=[post_addr_id], backref="post_customers")

    def __repr__(self):
        return "%s" %(self.name)

class Address(Base):
    __tablename__ = ‘address‘
    id = Column(Integer, primary_key=True)
    detail_address = Column(String(32))
    def __repr__(self):
        return "%s" %(self.detail_address)

Base.metadata.create_all(engine)

orms模块

from sqlalchemy.orm import sessionmaker
import orms

Session_class = sessionmaker(bind=orms.engine)
session = Session_class()
a1 = orms.Address(detail_address="BeiJing")
a2 = orms.Address(detail_address="ShangHai")
a3 = orms.Address(detail_address="TianJin")

session.add_all([a1, a2, a3])
# 注意这里赋值的牛逼之处!!!直接用对象进行赋值
c1 = orms.Customer(name="Alex", bill_addr=a1, post_addr=a2)
c2 = orms.Customer(name="Jack", bill_addr=a2, post_addr=a3)
c3 = orms.Customer(name="Rain", bill_addr=a3, post_addr=a3)

session.add_all([c1, c2, c3])
session.commit()

init_data模块

from sqlalchemy.orm import sessionmaker
import orms

Session_class = sessionmaker(bind=orms.engine)
session = Session_class()

alex = session.query(orms.Customer).filter(orms.Customer.name=="Alex").first()
print(alex.bill_addr, alex.post_addr)  # BeiJing ShangHai

sh = session.query(orms.Address).filter(orms.Address.detail_address=="ShangHai").first()
print(sh.bill_customers)  # [Jack]

原文地址:https://www.cnblogs.com/staff/p/9998761.html

时间: 2024-10-08 13:08:38

sqlalchemy外键的一些东西的相关文章

sqlalchemy外键和relationship查询

原文地址:https://www.cnblogs.com/goldsunshine/p/9269880.html 阅读目录 一.sqlalchemy体现的外键特性 二.外键和查询 前面的文章中讲解了外键的基础知识和操作,上一篇文章讲解了sqlalchemy的基本操作.前面两篇文章都是作为铺垫,为下面的文章打好基础.记得初一时第一次期中考试时考的不好,老爸安慰我说:“学习是一个循序渐进的过程”,而我的就是按照这样思路来学习数据库外键.首先是了解外键基础理论,然后是sqlalchemy基本操作,最后

吃货眼中的sqlalchemy外键和连表查询

前言 使用数据库一个高效的操作是连表查询,一条查询语句能够查询到多个表的数据.在sqlalchem架构下的数据库连表查询更是十分方便.那么如何连表查询?以及数据库外键对连表查询有没有帮助呢?本篇文章就这两个问题简单解释. 建表 俗话说巧妇难为无米之炊,连表查询肯定要有表,有数据库啊.那有没有数据库是你见了垂涎三尺的呢?中国文化博大精深,饮食文化更是璀璨的明珠.我们就以中国菜系为话题,讲一讲好吃的,顺便再说一说外键和连表查询. 鲁菜  山东菜系,而且在明清两代,宫廷御膳是以鲁菜为主,鲁菜味道浓厚,

【Flask】Sqlalchemy 外键

### 外键:使用SQLAlchemy创建外键非常简单.在从表中增加一个字段,指定这个字段外键的是哪个表的哪个字段就可以了.从表中外键的字段,必须和父表的主键字段类型保持一致.示例代码如下: 1 from sqlalchemy import create_engine, Column, Integer, String, Text, ForeignKey 2 3 from sqlalchemy.ext.declarative import declarative_base 4 from sqlal

Python 之 sqlalchemy 外键正反向关联查询

表内容: 代码: #Author Kang import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String,ForeignKey from sqlalchemy.orm import sessionmaker,relationship #创建对象的基类

sqlalchemy 外键

建表 from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy import Column,INT,VARCHAR,ForeignKey from sqlalchemy.orm import relationship class student(Base): __tablename__='student' id=Column(INT,primary_key=T

使用sqlalchemy的ORM创建外键关联时报错

在学习使用sqlalchemy模块的时候踩了一个坑,分享一下. 埋下隐患 我先用下面的语句创建了一张学生信息表: > CREATE TABLE student ( -> id INT UNSIGNED AUTO_INCREMENT, -> name VARCHAR(20) NOT NULL, -> age TINYINT, -> PRIMARY KEY (id) -> ); 表里就3个字段:自增id(无符号的数字,自增id不会是负数,当然用无符号,感觉自己好专业),na

sqlalchemy多外键关联

一.前言 如果有张表A的多个字段关联另一张表B的一个字段,就如同一个客户表的账单地址和发货地址,同时关联地址表中的id字段. 二.事例 # -*- coding: UTF-8 -*- from sqlalchemy import create_engine from sqlalchemy import Integer, ForeignKey, String, Column from sqlalchemy.ext.declarative import declarative_base from s

sqlalchemy操作----外键关联,relationship

... #!_*_coding:utf-8_*_ #__author__:"Alex huang" import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String,ForeignKey from sqlalchemy.orm import r

西游之路——python全栈——ORM之SQLAlchemy(3)外键与relationship的关系

目录 relationship是为了简化联合查询join等,创建的两个表之间的虚拟关系,这种关系与标的结构时无关的.他与外键十分相似,确实,他必须在外键的基础上才允许使用 不然会报错: sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Father.son - there are no foreign keys link