实例化对象会自动添加到SQLAlchemy Session。为什么?

时间:2016-01-26 12:12:56

标签: python session sqlalchemy

根据我对SQLAlchemy的理解,为了模型添加到会话I need to call session.add(obj)。但是,出于某种原因,在我的代码中,SQLAlchemy似乎自动执行此操作。

为什么要这样做,我怎么能阻止它呢?我是否以正确的方式接近会议?

示例

>>> from database import Session as db
>>> import clients
>>> from instances import Instance
>>> from uuid import uuid4
>>> len(db.query(Instance).all())
>>> 0 # Note, no instances in database/session
>>> i = Instance(str(uuid4()), clients.get_by_code('AAA001'), [str(uuid4())])
>>> len(db.query(Instance).all())
>>> 1 # Why?? I never called db.add(i)!

database.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base

import config

Base = declarative_base()

class Database():

    def __init__(self):
        db_url = 'postgresql://{:s}:{:s}@{:s}:{}/{:s}'.format(
            config.database['user'],
            config.database['password'],
            config.database['host'],
            config.database['port'],
            config.database['dbname']
        )
        self.engine = create_engine(db_url)
        session_factory = sessionmaker(bind=self.engine)
        self.session = scoped_session(session_factory)

Database = Database()

Session = Database.session

instance.py

from sqlalchemy import Column, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.postgresql import UUID, ARRAY

import database

Base = database.Base

class Instance(Base):
    __tablename__ = 'instances'

    uuid = Column(UUID, primary_key=True)
    client_code = Column(
        Text, ForeignKey('clients.code', ondelete='CASCADE'), nullable=False)
    mac_addresses = Column(ARRAY(Text, as_tuple=True),
                           primary_key=True)

    client = relationship("Client", back_populates="instances")

    def __init__(self, uuid, client, mac_addresses):
        self.uuid = uuid
        self.client = client
        self.mac_addresses = tuple(mac_addresses)

client.py

from sqlalchemy import Column, Text
from sqlalchemy.orm import relationship

import database
from database import Session as db

Base = database.Base

class Client(Base):
    __tablename__ = 'clients'

    code = Column(Text, primary_key=True)
    name = Column(Text)

    instances = relationship("Instance", back_populates='client')

    def __init__(self, code, name=None):
        self.code = code
        self.name = name

def get_by_code(code):
   client = db.query(Client).filter(Client.code == code).first()
   return client

1 个答案:

答案 0 :(得分:2)

当您创建SQLAlchemy对象并将其直接链接到另一个SQLAlchemy对象时,两个对象都会在会话中结束。

原因是SQLAlchemy需要确保您可以查询这些对象。 例如,带有地址的用户。

如果您在代码中创建具有地址的用户,则用户和地址都会在会话中结束,因为该地址链接到用户,而SQLAlchemy需要确保您可以使用地址查询用户的所有地址user.addresses.all()。

在这种情况下,需要提取所有(可能的)现有地址,以及刚刚添加的新地址。为此,需要将新添加的地址保存在数据库中 为了防止这种情况发生(例如,如果您只需要对象来计算),您可以将对象与其ID /外键链接:

address.user_id = user.user_id

但是,如果这样做,您将无法再访问SQLAlchemy属性。因此user.addressesaddress.user将不再产生结果。

反过来也是如此;我自己问了一个问题为什么用ID链接两个对象不会导致SQLAlchemy在ORM中链接这些对象:

relevant stackoverflow question

another description of this behavior