0

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 ??

4
  • Why can't you do the exact same thing? Commented Jun 1, 2016 at 18:01
  • @univerio wouldn't that insert records 2 times ? As once i have already done by extending the user.successes. Commented Jun 1, 2016 at 18:10
  • Have you tried it? 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. Commented Jun 1, 2016 at 18:23
  • @univerio yes I tried it, and it worked. thanks :) You should post this as an answer and I'll mark it as solved. Commented Jun 17, 2016 at 21:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.