pythonflasksqlalchemywtforms

SQLAlchemy populate children when adding parent


I have a class called User. This User has a relationship to another class called Membership:

class User(db.Model):
    __tablename__ = 'Users'
    id = db.Column(db.Integer, primary_key=True, unique=True)
    first_name = db.Column(db.String(24), unique=False)
    last_name = db.Column(db.String(24), unique=False)
    email_address = db.Column(db.String(50), unique=True)
    memberships = db.relationship("Membership")

class Membership(db.Model):
    __tablename__ = 'Memberships'
    id = db.Column(db.Integer, primary_key=True, unique=True)
    user_id = db.Column(db.Integer, db.ForeignKey('Users.id'))
    membership = db.Column(db.String(200), unique=False)

Now i have a form called "AddUserForm" which is a WTForm. This form has some required field (that populate the User class) and has a non-required field for the memberships.

My question is if its possible to populate the Membership at the same time as the User without the user existing beforehand.

For example i am adding the user like:

def add_user():
    form = AddUserForm()
    new_user = User(first_name=form.first_name.data, last_name=form.last_name.data,email_address=form.email_address.data)

Now since the User does not exist i cant really manually add a membership since i need to use User.id as user_id but i dont know it since the user is not yet created.

Is there a way to include the membership in the creation of the new user so that it would add it based on the relationship between the two classes?


Solution

  • Taking a chance here:

    def add_user():
        form = AddUserForm()
        new_user = User(first_name=form.first_name.data, last_name=form.last_name.data,email_address=form.email_address.data)
        new_membership = Membership(membership="The best ship is a membership")
        new_user.memberships = [new_membership]
        session.add_all([new_user, new_membership])
        session.save()