SQLAlchemy:关联对象的自定义外部条件

2024-10-01 02:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:如何在创建的关联对象(CustomerLeasSociation)上添加ON条件,使IsDisabled属性必须等于1?你知道吗

我试图为自定义条件添加primaryjoin参数,但似乎不起作用。你知道吗

目标:必须筛选关联对象属性(IsDisabled)的联接条件。你知道吗

错误: 参数错误:关系Cus客户协会无法根据联接条件和远程参数确定任何明确的本地/远程列对。考虑使用remote()注释来准确地标记连接条件中位于关系远端的那些元素。你知道吗

from sqlalchemy import Column,Integer,String,Table,ForeignKey, and_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, foreign, remote
from sqlalchemy.ext.associationproxy import association_proxy
import logging

Base = declarative_base()

logger = logging.getLogger(__name__)

class MyModel():

    def __init__(self):
        self.customer = self.Customer()
        self.role = self.Role()
        logger.info("Model Initialized")

    class CustomerRoleAssociation(Base):
        __tablename__ = 'customer_role'


        CustomerRoleId = Column(Integer, primary_key=True)
        CustomerId = Column(Integer, ForeignKey('customer.CustomerId'))
        RoleId = Column(Integer, ForeignKey('role.RoleId'))
        IsDisabled = Column(Integer)

        Customer = relationship("Customer",backref="role_associations",primaryjoin="and_(CustomerRoleAssociation.CustomerId==Customer.CustomerId,CustomerRoleAssociation.IsDisabled!=1)")
        Role = relationship("Role", backref="customer_associations",primaryjoin="and_(CustomerRoleAssociation.CustomerId==Customer.CustomerId,CustomerRoleAssociation.IsDisabled!=1)")

    class Customer(Base):

        __tablename__ = 'customer'

        CustomerId = Column(Integer, primary_key = True)
        UserName = Column(String)
        IsDisabled = Column(Integer)
        IsDeleted = Column(Integer)

        CustomerRoles = association_proxy("role_associations", "Role", 
                        creator=lambda r: CustomerRoleAssociation(Role=r))

        logger.info("Customer Model Initialized")

    class Role(Base):

        __tablename__ = 'role'

        RoleId = Column(Integer, primary_key = True)
        RoleName = Column(String)
        IsDisabled = Column(Integer)
        IsDeleted = Column(Integer)

        RoleCustomers = association_proxy("customer_associations", "Customer", 
                        creator=lambda c: CustomerRoleAssociation(Customer=c))                        

        logger.info("Role Model Initialized")

Tags: fromimportselfbasesqlalchemycolumnintegercustomer