简体   繁体   中英

flask-sqlalchemy relationship between tables issue

I'm trying to build dashboard for admins who can manage some settings about their organizations.

below are 2 tables, Users and Organization, when someone register it supposed to create the user and organization with relationship between them, but after I try to register I get the following error (sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: user.org_id)

which makes sense, but i'm not sure how can I create the user and the organization that he belongs to and also add the organization ID in the user table at the same time?

or is this database design wrong?

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(20), nullable=False)
    last_name = db.Column(db.String(20), nullable=False)
    display_name = db.Column(db.String(40), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
    date_joined = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    image_file = db.Column(db.String(20), nullable=False, default="default.jpg")
    org_id = db.Column(db.Integer, db.ForeignKey("organization.id"), nullable=False)



class Organization(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    domain = db.Column(db.String(20), unique=True, nullable=False)
    date_joined = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    logo_file = db.Column(db.String(20), nullable=False, default="default.jpg")
    sub_type = db.Column(db.String(20), nullable=False, default="Demo")
    sub_start_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    sub_end_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    status = db.Column(db.String(20), nullable=False, default="Active")
    admins = db.relationship("User", backref="admin", lazy=True)

    def __repr__(self):
        return f"User('{self.email}')"
    @users.route("/register", methods=["GET", "POST"])
    def register():
        if current_user.is_authenticated:
            return redirect(url_for("main.dashboard"))
        form = RegistrationForm()
        if form.validate_on_submit():
            hashed_password = bcrypt.generate_password_hash(form.password.data).decode(
                "utf-8"
            )
    
            organization = Organization(
                domain=form.email.data.split("@")[1],
            )
            admin = User(
                first_name=form.first_name.data,
                last_name=form.last_name.data,
                display_name=form.first_name.data + " " + form.last_name.data,
                email=form.email.data,
                password=hashed_password,
            )
            db.session.add(organization)
            db.session.add(admin)
            db.session.commit()
            flash("Your account has been created! You are now able to log in", "success")
            return redirect(url_for("users.login"))
        return render_template("users/register.html", title="Register", form=form)

When you have nullable set as False on User.org_id, you will need to assign the org_id to the User when you first create it. You should create the organization first, then create the user with org_id assign to it. Your code should look something like this instead

organization = Organization(
            domain=form.email.data.split("@")[1],
        )
        db.session.add(organization)
        db.session.commit() #Need to create the organization first to obtain the id
        admin = User(
            first_name=form.first_name.data,
            last_name=form.last_name.data,
            display_name=form.first_name.data + " " + form.last_name.data,
            email=form.email.data,
            password=hashed_password,
            org_id=organization.id
        )
        db.session.add(admin)
        db.session.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM