一对一关系sqlalchemy烧瓶

时间:2017-06-06 18:19:33

标签: flask flask-sqlalchemy

我正在尝试为用户和个人资料表格实现1-1关系,如下所示。

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime(), default=datetime.now())

    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

    def __repr__(self):
        return '<User {self.email}>'.format(self=self)


class CustomerProfile(db.Model):
    __tablename__ = 'customer_profiles'
    id = db.Column(db.Integer(), primary_key=True)
    full_name = db.Column(db.String(200), nullable=True)

    user_id = db.Column(db.Integer(), db.ForeignKey('user.id'), unique=True)
    user = db.relationship('User', backref=db.backref("CustomerProfile", uselist=False))

    def __repr__(self):
        return '<CustomerProfile {self.full_name}>'.format(self=self)

我的问题是:

这是1-1映射的正确表示吗?因为当我尝试使用MySQL Workbench对数据库进行逆向工程时,它确实向我展示了一对多的映射 如果这是正确的表示,则允许插入重复行,除非我在user_id 中给出unique = True。我原本以为我告诉MySql关于映射,它不应该允许重复行......这不是真的吗?

看了http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-one

之后

我将代码更改为以下内容:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime(), default=datetime.now())

    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

    customer_profiles = db.relationship('CustomerProfile', uselist=False, back_populates="user")

    def __repr__(self):
        return '<User {self.email}>'.format(self=self)


class CustomerProfile(db.Model):
    __tablename__ = 'customer_profiles'
    id = db.Column(db.Integer(), primary_key=True)
    full_name = db.Column(db.String(200), nullable=True)

    user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
    user = db.relationship('User', back_populates='customer_profiles')

    def __repr__(self):
        return '<CustomerProfile {self.full_name}>'.format(self=self)

但是,我仍然可以在配置文件中插入重复的行....

由于我在数据库级别映射它,我假设DB会阻止我插入重复的行,即使我没有给出unique = True ..我的理解是否正确?

0 个答案:

没有答案