sqlalchemy foreign key

A table

from sqlalchemy.orm import relationship
from sqlalchemy import Column
from sqlalchemy import Integer,String,ForeignKey

class Depart(Base):
    __tablename__ = 'depart'
    id = Column(Integer, primary_key=True)
    title = Column(String(32), index=True, nullable=False)

class Users(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name Column = (String (32), index = True, Nullable = False) 
    depart_id = Column (Integer, ForeignKey ( " depart.id " ))
     # dp create contact, do not create field 
    dp = Relationship ( " Depart's " , backref = ' Pers ' )

Second, data manipulation

# 1 query for all users in the organization. + 
RET = session.query (users.id, Users.name, Depart.title) .join (Depart's, Users.depart_id == Depart.id) .all ()
 for Row in RET :
     Print (row.id, row.name, row.title) 

# left the Join, SQL statement 
query = session.query (users.id, Users.name, Depart.title) .join (Depart, Users.depart_id == Depart .id, isouter = True)
 Print (query) 

# 2. in the Relation field: + query all users in the organization. ====> forward inquiry recommended 
RET = session.query (the users) .all ()
 for Row in RET:
     Print (row.id, row.name, row.depart_id, row.dp.title) 

#3. relation fields: Query all personnel ======= Sales> reverse lookup recommended 
obj = session.query (Depart's) .filter (Depart.title == ' sales ' ) .first ()
 for Row in obj.pers:
     Print (row.id, row.name, obj.title) 

# 4. create a name called: IT department, then add in the sector employee: a 
# way a: 
d1 = Depart's (title = ' the IT ' ) 
session.add (D1) 
Session.commit () 
#
 U1 = the Users (name = ' A ' , depart_id = d1.id) 
session.add (U1) 
Session.commit () 

# way: using Relation 
U1 = the Users (name = ' A' , Dp = Depart's (title = ' IT ' )) 
session.add (U1) 
Session.commit () 

# 5. Create a name called: cleaning department, add more employees in the sector: a / b / C 
D1 = Depart's (title = ' cleaning ' ) 
d1.pers = [the Users (name = ' A ' ), the Users (name = ' B ' ), the Users (name = ' C ' ),] 
session.add (D1) 
session.commit ()

 

Guess you like

Origin www.cnblogs.com/wt7018/p/11617825.html