So if i'm reading correctly you have two model classes User
and Credential
which is a one-to-many relationship:
class User(db.Model):
...
credentials = db.relationship('Credential')
class Credential(db.Model):
...
user_id = db.Column(db.Integer, db.ForeignKey('user.id', nullable=False)
Is it possible to add an additional foreignkey to signify a one-to-one relationship:
class User(db.Model):
...
active_credential_id = db.Column(db.Integer, db.ForeignKey('credential.id'))
class Credential(db.Model):
...
active_user = db.relationship('User')
You could update this with something like:
inactive_credential = # some credential from the user's list of credentials
user = User.query.filter(User.id == inactive_credential.user_id)
user.active_credential_id = inactive_credential.id
db.session.add(user)
db.session.commit()
# inactive_credential ==>> active_credential
The use of a foreign key here maintains database integrity.
You will need some additional constraint that says an active_credential_id can only be selected from the list of credentials whose user is defined by user_id. I just thought of this at the end and will update answer later if I have solution.