user3787291
user3787291

Reputation: 227

Flask-SQLAlchemy insert records with multiple foreign keys

I have 3 tables:

class User(db.Model):
   id = db.Column(db.Integer, primary_key=True)
   name = db.Column(db.String)
   successes = db.relationship('Success', backref='user', lazy='dynamic')

class Success(db.Model):
   id = db.Column(db.Integer, primary_key=True)
   package = db.Column(db.String)
   user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
   trial_id = db.Column(db.Integer, db.ForeignKey('trials.id'))

class Trials(db.Model):
   id = db.Column(db.Integer, primary_key=True)
   description = db.Column(db.String)
   successes = db.relationship('Success', backref='attempt', lazy='dynamic')

I can insert the data in Success and user table using :

user.successes.extend(success_objects_list)
db.session.add(user)
db.session.add_all(success_objects_list)
db.session.commit()

This takes care of the foreign-key user_id.

How do I simultaneously insert data data in Trial Table and take care of the second foreign-Key trial_id ??

Upvotes: 0

Views: 1888

Answers (1)

univerio
univerio

Reputation: 20508

You can do the exact same thing with trial.successes and it should just work. By extending user.successes you add the Success instances to the session and associate them with the User instance. By extending trial.successes, you add the Success instances to the session and associate them with the Trials instance, but because they are already in the session, they don't get added twice.

Upvotes: 1

Related Questions