I have created the following model:
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(1024), nullable=False)
email = db.Column(db.String(250), nullable=True, unique=True)
code = db.Column(db.String(10), nullable=False, unique=True)
There are some cases in which a Person turnos into a system user. So, I have the following model:
class User(Person):
password = db.Column(db.String(1024), nullable=False)
The problem, I that when I try to create an User from a Person doing this:
>>> person = Person(name='foobar', email='[email protected]', code='123123')
>>> db.session.add(person)
>>> db.session.commit()
>>> print person.id
4
>>> user = User(id=4, password='changeme')
>>> db.session.add(user)
>>> db.session.commit()
(IntegrityError) null value in column "name" violates not-null constraint
'INSERT INTO person (id, name, ....
The question is how can I prevent of the model User creating a new Person instance because that already exists on the database?
UPDATE: when trying Join table inheritance, I have the same problem. It don't understand how not to create a new instance of Person
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(1024), nullable=False)
email = db.Column(db.String(250), nullable=True, unique=True)
code = db.Column(db.String(10), nullable=False, unique=True)
person_type = db.Column(db.String(10), nullable=False)
__mapper_args__ = {'polymorphic_on': 'person_type'}
class User(Person):
__mapper_args__ = {'polymorphic_identity': 'recurvado'}
id = db.Column(db.Integer, db.ForeignKey('arco.id'), primary_key=True)
password = db.Column(db.String(1024), nullable=False)
The problem, I that when I try to create an User from a Person doing this:
>>> person = Person(name='foobar', email='[email protected]', code='123123')
>>> db.session.add(person)
>>> db.session.commit()
>>> print person.id
4
>>> user = User(id=4, password='changeme')
>>> db.session.add(user)
>>> db.session.commit()
(IntegrityError) null value in column "name" violates not-null constraint
'INSERT INTO person (id, name, .
name, acodeand whatever else has aNOT NULLconstraint. From your example I understand that you just want to do this:user = User(name='foobar', email='foobar...', password='changeme'); session.add(user); session.commit()ThePersonclass does not need to be involved. Also, I don't think you can have a non-null password when using joined inheritance, all yourPersons will raise integrity errors toouser = session.query(User).get(4); user.password = '...'If not, perhaps this:person = session.query(Person).get(4); person.person_type = 'recurvado' ;session.commit() user = session.query(User).get(4)