SQLAlchemy use of foreign keys

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.