Skip to content

One to One Relationship

Rajesh Khadka edited this page Dec 2, 2019 · 1 revision

We will be exploring the one to one relationship in sqlalchemy. User will maintain the relationship between user and profile as:

class User(db.Model):
    id = db.Column(db.String(), primary_key=True, default=str(uuid.uuid4()))
    email = db.Column(db.String(), nullable=False)
    password = db.Column(db.String(), nullable=False)
class Profile(db.Model):

    def __init__(self, name, address, phone):
        self.name = name
        self.address = address
        self.phone = phone

    id = db.Column(db.String(), primary_key=True, default=str(uuid.uuid4()))
    name = db.Column(db.String())
    address = db.Column(db.String())
    phone = db.Column(db.String())
    user_id = db.Column(db.String(), db.ForeignKey('user.id'))
    user = db.relationship('User', backref=db.backref('profile', uselist=False))

we can maintain one to one relationship by using the relationship attribute in model class as :

user = db.relationship('User', backref=db.backref('profile', uselist=False))

backref creates the virtual field named profile on the Model class User. We are using uselist=False because its not one to many relationship.

We can access the user profile while inserting data into a profile attribute.

user = User(email='a@gmail.com', password='password')
profile = Profile(name='Jhon', phone='+1-23232323', address='USA')
user.profile = profile
db.session.add(user)
db.session.commit()

You can find the implementation over this commit