ORM can encapsulate the data stored in the database into objects, and all database operations can be encapsulated in the object if the package is good. Such code can be very clear in the organization structure, and the relative and use of SQL statements in SQL injection will be very slow.
There are four kinds of mappings in SQLAlchemy, one to many, the other to the other, the other to many.
Implementing this mapping requires only foreign keys (ForeignKey), and relationship
Pair of more:
From sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, Charfrom SQLAlchemy Import foreignkeyfrom sqlalchemy.orm import relationship, backrefbase = Declarative_base () class Parent (base): __ table__ = "parent" id = column (Integer, primary_key=true) name = Column (CHAR ()) Child = Relationship (" Child ", backref=" parent ") class child (Base): __table__ =" Child " id = Column (Integer, primary_key=true) Name = Column (CHAR ()) parent_id = column (Integer,foreignkey (' parent.id '))
Many-to-one: (recommended)
From sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, Charfrom SQLAlchemy Import foreignkeyfrom sqlalchemy.orm import relationship, backrefbase = Declarative_base () class Parent (base): __ table__ = "parent" id = column (Integer, primary_key=true) name = Column (CHAR ()) class child (Base): __ table__ = "Child" id = column (integer, primary_key=true) name = Column (CHAR ()) parent_id = column (integer , ForeignKey (' parent.id ')) parent = relationship ("parent", backref= "child")
SQLAlchemy use of foreign keys