当前位置:网站首页>[flask] ORM one-to-one relationship
[flask] ORM one-to-one relationship
2022-07-02 08:35:00 【YZL40514131】
stay sqlalchemy in , If you want to map two models into a one-to-one relationship , Then it should be in the parent model , When specifying references , To pass a uselist=False
Enter this parameter . Is to tell the parent model , When quoting this slave model in the future , It's no longer a list , It's an object .
Method 1 : Refer to one to many Association , hold uselist=false, Add to objects without foreign keys , Others are the same as the previous one to many relationship
Configuration database 、 Create database engine 、 Create base class
from sqlalchemy import create_engine, Column, Integer, ForeignKey, String, TEXT, Boolean, DATE, DECIMAL
from sqlalchemy.ext.declarative import declarative_base
from datetime import date
from sqlalchemy.orm import sessionmaker,relationship,backref
# Configuration variables of the database
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'test'
USERNAME = 'root'
PASSWORD = 'root'
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
# Create database engine
engine=create_engine(DB_URI)
# Create model class base class
Base=declarative_base(engine)
# establish session object
session=sessionmaker(engine)()
Create model classes
class Person(Base):
__tablename__='t_person' # Create table name , It is best to t_ start
id=Column(name='id',type_=Integer,primary_key=True,autoincrement=True)
name=Column(name='name',type_=String(255))
age=Column(name='age',type_=Integer)
address=Column(name='address',type_=String(255))
country=Column(name='country',type_=String(50))
city=Column(name='city',type_=String(50))
# The ID card corresponding to the current person
id_card=relationship('ID_Card')
def __str__(self):
return f'Person- Number {
self.id} full name {
self.name} Annual collar {
self.age}
class ID_Card(Base):
__tablename__ = 't_id_card'
card_number = Column(name='card_number', type_=String(18), primary_key=True)
p_id=Column(Integer,ForeignKey('t_person.id'))
# Indicates the person corresponding to the ID card
person=relationship('Person')
def __str__(self):
return f"ID_Card- ID number {
self.card_number}"
Query data
1、 Query name python Identity card number :
def select():
p1=session.query(Person).filter(Person.name=='python').first()
print(p1) # Name is python Your character information
print(p1.id_card) # Name is python Your ID card information
print(p1.id_card.card_number) # Name is python Identity card number
Person- Number 1 full name python Annual collar 18
ID_Card- ID number 112121212
112121212
2、 Check the ID number 112121212 Who is it? ?
def select():
# Check the ID number 112121212 Who is it? ?
id1=session.query(ID_Card).filter(ID_Card.card_number=='112121212').first()
print(id1) # The ID card is 112121212 Your ID card information
print(id1.person) # The ID card is 112121212 Your character information
print(id1.person.name) # The ID card is 112121212 Character name of
ID_Card- ID number 112121212
Person- Number 1 full name python Annual collar 18
python
Method 2 : Recommended
Particular attention :uselist=False: tell id_card It's not a list
Human information table
class Person(Base):
__tablename__='t_person' # Create table name , It is best to t_ start
id=Column(name='id',type_=Integer,primary_key=True,autoincrement=True)
name=Column(name='name',type_=String(255))
age=Column(name='age',type_=Integer)
phone = Column(name='phone', type_=String(11), unique=True)
address=Column(name='address',type_=String(255))
country=Column(name='country',type_=String(50))
city=Column(name='city',type_=String(50))
# The ID card corresponding to the current person ,uselist=False: tell id_card It's not a list
#id_card=relationship('ID_Card',uselist=False)
def __str__(self):
return f'Person- Number {
self.id} full name {
self.name} Annual collar {
self.age}'
ID card form
class ID_Card(Base):
__tablename__ = 't_id_card'
card_number = Column(name='card_number', type_=String(18), primary_key=True)
p_id=Column(Integer,ForeignKey('t_person.id'))
# Indicates the person corresponding to the ID card ,
person=relationship('Person',backref=backref('id_card',uselist=False))
def __str__(self):
return f"ID_Card- ID number {
self.card_number}"
Particular attention 2:person=relationship(‘Person’,backref=backref(‘id_card’,uselist=False)) Writing
Query data
1、 Query name python Identity card number :
def select():
p1=session.query(Person).filter(Person.name=='python').first()
print(p1) # Name is python Your character information
print(p1.id_card) # Name is python Your ID card information
print(p1.id_card.card_number) # Name is python Identity card number
Person- Number 1 full name python Annual collar 18
ID_Card- ID number 112121212
112121212
2、 Check the ID number 112121212 Who is it? ?
def select():
id1=session.query(ID_Card).filter(ID_Card.card_number=='112121212').first()
print(id1) # The ID card is 112121212 Your ID card information
print(id1.person) # The ID card is 112121212 Your character information
print(id1.person.name) # The ID card is 112121212 Character name of
ID_Card- ID number 112121212
Person- Number 1 full name python Annual collar 18
python
Update data
3、 Call your cell phone 13888888888 The ID number of the person of is changed to “666666666”
def update():
res=session.query(Person).filter(Person.phone=='13888888888').first()
res.id_card.card_number='666666666'
session.commit()
4、 Number your ID card 3 Information about , The name of the person is changed to zhilong
def update():
res1=session.query(ID_Card).filter(ID_Card.card_id==3).first()
print(res1.person)
res1.person.p_name='zhilong'
session.commit()
Delete data
5、 Call your cell phone 13111118 Delete the character information of
def delete():
res2=session.query(Person).filter(Person.phone=='1311118').first()
session.delete(res2)
session.commit()
6、 Call your cell phone 1311115 The identity card information of the person information is deleted
def delete():
res2 = session.query(Person).filter(Person.phone == '1311115').first()
print(res2.id_card)
session.delete(res2.id_card)
session.commit()
7、 Number your ID card 2 Delete the character information of
def delete():
res3=session.query(ID_Card).filter(ID_Card.card_id==2).first()
session.delete(res3.person)
session.commit()
Problems that may occur when creating tables :
sqlalchemy.exc.InvalidRequestError: On relationship ID_Card.person, ‘dynamic’ loaders cannot be used with many-to-one/one-to-one relationships and/or uselist=False.
Because lazy loading is added to the model class , The one-to-one mode does not require lazy loading
FALSE :
id_card=relationship('ID_Card',backref=backref('person',lazy='dynamic',uselist=False))
The right is
id_card=relationship('ID_Card',backref=backref('person',uselist=False))
边栏推荐
- Routing foundation - dynamic routing
- Opencv common method source link (continuous update)
- 程序猿学英语-Learning C
- zipkin 简单使用
- Web security -- Logical ultra vires
- 【无标题】
- Chinese garbled code under vscade
- Programming ape learning English - imperative programming
- Deep understanding of JVM
- Li Kou daily one question brushing summary: binary tree chapter (continuous update)
猜你喜欢
Web安全--核心防御机制
Intelligent manufacturing solutions digital twin smart factory
Use the kaggle training model and download your own training model
2022 Heilongjiang's latest eight member (Safety Officer) simulated test question bank and answers
方法递归(斐波那契数列,青蛙跳台阶,汉诺塔问题)
Nacos 下载启动、配置 MySQL 数据库
Solid principle: explanation and examples
IP protocol and IP address
HCIA - data link layer
[untitled]
随机推荐
Summary of one question per day: stack and queue (continuously updated)
sqli-labs第1关
STM32 new project (refer to punctual atom)
Comparable,Comparator,Clonable 接口使用剖析
Sqlyog remote connection to MySQL database under centos7 system
Chrome debugging
Chinese garbled code under vscade
[untitled]
2022 Heilongjiang's latest eight member (Safety Officer) simulated test question bank and answers
Hcia - Application Layer
Linked list classic interview questions (reverse the linked list, middle node, penultimate node, merge and split the linked list, and delete duplicate nodes)
Use Wireshark to grab TCP three handshakes
Classes and objects (instantiation of classes and classes, this, static keyword, encapsulation)
Use the kaggle training model and download your own training model
TCP/IP—传输层
Implementation of bidirectional linked list (simple difference, connection and implementation between bidirectional linked list and unidirectional linked list)
W10 is upgraded to W11 system, but the screen is black, but the mouse and desktop shortcuts can be used. How to solve it
Li Kou daily one question brushing summary: binary tree chapter (continuous update)
ARP and ARP Spoofing
Web安全--核心防御机制