如何在SQLAlchemy的连接表继承中从父类创建子类?

时间:2012-10-28 13:16:58

标签: python sqlalchemy

我正在开发一个小型数据库,其中人员多于用户,因此目前有以下型号。

class Person(db.Model):
  __tablename__ = 'people'
  id       = db.Column(db.Integer, primary_key = True)
  forename = db.Column(db.String(64))
  surname  = db.Column(db.String(64))

  memberships = db.relationship('Membership', backref='person')

  @property
  def name(self):
    return self.forename + ' ' + self.surname

  def __repr__(self):
    return '<Person %r %r>' % (self.forename, self.surname)

class User(Person):
  __tablename__ = 'users'
  id       = db.Column(db.Integer, db.ForeignKey('people.id'), primary_key = True)
  email    = db.Column(db.String(120), index = True, unique = True)
  role     = db.Column(db.SmallInteger, default = ROLE_USER)

  salt     = db.Column(db.BINARY(8))
  password = db.Column(db.BINARY(20))

  def __repr__(self):
    return '<User %r>' % (self.email)

它工作得很好,因为如果我创建一个用户,那么一个人也会得到保存。当人员已存在于数据库中时,问题是创建用户。

我尝试了以下内容:

>>> p = models.Person.query.get(3)
>>> u = models.User(id=p.id, email="example@example.com")
>>> u.set_password('password')
>>> db.session.add(u)
>>> db.session.commit()
Traceback
...
sqlalchemy.exc.IntegrityError: (IntegrityError) PRIMARY KEY must be unique u'INSERT INTO people (id, forename, surname) VALUES (?, ?, ?)' (3, None, None)

我做错了什么?有没有办法从人员创建用户?

1 个答案:

答案 0 :(得分:1)

Michael Bayer's advice上,我改变了多态设计并改为使用了构图。代码如下:

class Person(db.Model):
  __tablename__ = 'people'
  id       = db.Column(db.Integer, primary_key = True)
  forename = db.Column(db.String(64))
  surname  = db.Column(db.String(64))

  memberships = db.relationship('Membership', backref='person')

  @property
  def name(self):
    return self.forename + ' ' + self.surname

  def __repr__(self):
    return '<Person %r %r>' % (self.forename, self.surname)

class User(db.Model):
  __tablename__ = 'users'
  id       = db.Column(db.Integer, db.ForeignKey('people.id'), primary_key = True)
  email    = db.Column(db.String(120), index = True, unique = True)
  role     = db.Column(db.SmallInteger, default = ROLE_USER)

  salt     = db.Column(db.BINARY(8))
  password = db.Column(db.BINARY(20))

  person   = db.relationship('Person')

与问题中的那个会话的类似会话将为......

>>> p = models.Person.query.get(3)
>>> u = models.User(person=p, email="example@example.com")
>>> u.set_password('password')
>>> db.session.add(u)
>>> db.session.commit()
>>>