1

我正在尝试在两个表之间建立关系。

实例化模型时出现以下错误:

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)'.

核心/模型.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

用户/模型.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__
    )

以下声明会发生错误:

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

1 回答 1

1

似乎有些代码您没有发布,因为仅运行此代码也会给您带来其他错误(例如,与__tablename__未正确设置的属性有关)。但是,您收到的实际错误可能与此代码有关...

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

根据关系函数的文档,第一个参数应该是......

一个映射类,或实际的 Mapper 实例,表示关系的目标。

但是,您正在使用__tablename__属性,它应该只是表的名称(字符串)。

因此,尝试将其更改为...

@declared_attr
def activation(self):
    return relationship(
      Activation,
      backref=self.__tablename__
    )
于 2013-10-05T20:44:25.377 回答