简体   繁体   English

表问题之间的flask-sqlalchemy关系

[英]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)下面是 2 个表,用户和组织,当有人注册它应该创建用户和组织之间的关系时,但在我尝试注册后,我收到以下错误(sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL约束失败: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?这是有道理的,但我不确定如何创建用户和他所属的组织,同时在用户表中添加组织 ID?

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.当您在 User.org_id 上将 nullable 设置为 False 时,您需要在首次创建时将 org_id 分配给用户。 You should create the organization first, then create the user with org_id assign to it.您应该首先创建组织,然后创建分配 org_id 的用户。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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