2013-10-05 2 views
1

두 테이블 간의 관계를 만들려고합니다.sqlalchemy 관계 설정

나는 다음과 같은 오류 얻을 모델 인스턴스화 할 때 가

:

from core.models import Activation 
a = Activation() 
ArgumentError: Class object expected, got 'Table(u'activations', MetaData(bind=Engine(postgresql+psycopg2://localhost:5432/mydb)), Column('id', Integer(), table=<activations>, primary_key=True, nullable=False), Column('valid_until', DateTime(), table=<activations>), Column('code', Unicode(length=30), table=<activations>, nullable=False), Column('created_by', Unicode(length=16), table=<activations>, nullable=False), schema=None)'. 

코어/models.py

class ActivationMixin(Base): 

    @declared_attr 
    def code(self): 
    return Column(Unicode(30), nullable=False, unique=True) 

    @declared_attr 
    def valid_until(self): 
    return Column(DateTime, nullable=True) 

    @declared_attr 
    def created_by(self): 
    return Column(Unicode(16), nullable=False) 

    @classmethod 
    def get_by_code(cls, request, code): 
    session = get_session(request) 
    return session.query(cls).filter(cls.code == code).first() 

    def __init__(self, created_by='web', valid_until=None): 
    """Create a new activation. *valid_until* is a datetime. 
    It defaults to 3 days from current day. 
    """ 
    self.code = generate_random_string(24) 
    self.created_by = created_by 

    if valid_until: 
     self.valid_until = valid_until 
    else: 
     self.valid_until = datetime.utcnow() + timedelta(days=3) 

class Activation(ActivationMixin): 
    pass 

사용자/오류가 models.py

class User(Base): 
    email = Column(Unicode(256), nullable=False, unique=True) 
    status = Column(Boolean, default=False) 
    salt = Column(Unicode(32), nullable=False) 
    _password = Column('password', Unicode(256), nullable=False) 
    logins = Column(Integer, default=0) 
    last_login = Column(
     TIMESTAMP(timezone=False), 
     default=func.now(), 
     server_default=func.now(), 
     nullable=False 
) 
    account_type = Column(AccountType.db_type()) 

    @declared_attr 
    def activation_id(self): 
    return Column(
     Integer, 
     ForeignKey('%s.id' % (Activation.__tablename__)) 
    ) 

    @property 
    def is_activated(self): 
    if self.activation_id is None: 
     return True 

    return False 

    @declared_attr 
    def activation(self): 
    return relationship(
     Activation.__tablename__, 
     backref=self.__tablename__ 
    ) 

함께 occures 다음 선언 :

@declared_attr 
def activation(self): 
    return relationship(
     Activation.__tablename__, 
     backref=self.__tablename__ 
    ) 

답변

1

이 코드를 실행하면 다른 오류도 발생할 수 있으므로 게시하지 않은 코드가있는 것 같습니다 (예 : __tablename__ 속성이 적절하게 설정되지 않음). 그러나 점점 실제 오류는있다, 그러나 ... relationship function에 대한 설명서에 따르면

@declared_attr 
def activation(self): 
    return relationship(
     Activation.__tablename__, 
     backref=self.__tablename__ 
    ) 

는 첫 번째 인수가 있어야한다 ...

a mapped class, or actual Mapper instance, representing the target of the relationship.

이 코드에 아마 관련이 __tablename__ 속성을 사용합니다.이 속성은 테이블 이름 (문자열)이어야합니다.

그래서,이 변화 시도 ... 바로 그 것이었다

@declared_attr 
def activation(self): 
    return relationship(
     Activation, 
     backref=self.__tablename__ 
    ) 
+0

감사합니다. – slik

관련 문제