如何记录到具有一对多关系的数据库?

How to record to record to a database with one-to-many relationship?

我正在尝试做一个小项目,但在 SQLAlchemy 中的数据库结构方面遇到了一些困难。我有两个数据库模型(下面的代码)。

  1. 在注册表单中创建用户模型并将其添加到数据库中。
  2. 然后我需要找到一种方法来为已登录用户的个人资料添加客户端。

问题: 我怎么做?我需要专门为登录用户创建一条记录。因此,当我显示它们(他的客户)时,它们只会显示给该特定用户。

class 用户(UserMixin,db.Model): 表名 = 'user'

id = db.Column(db.Integer, primary_key=True)
company_name = db.Column(db.String(120), index=True, unique=False)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
clients = db.relationship('Client', backref='invoice_clients', lazy='dynamic')

class 客户端(db.Model): 表名 = 'client'

id = db.Column(db.Integer, primary_key=True)
client_name = db.Column(db.String(140))
client_company = db.Column(db.String(140))
client_email = db.Column(db.String(140))
invoice_amount = db.Column(db.Integer)
service_description = db.Column(db.String)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

我希望当用户从他的个人资料页面添加客户时 - 它只会为他记录在数据库中。

首先,我相信你的backref参数是反了。那就是你可以在引用对象上使用的属性到"get back"到当前的class。所以它应该看起来像这样:

class User(UserMixin, db.Model):
    __tablename__ = 'user'

    clients = db.relationship('Client', backref='user', lazy='dynamic')

关于为特定用户添加客户端的问题,您可以通过两种方式解决。您可以手动完成:

# Or flask_login, or whatever you're using for user management
from flask_security import current_user

new_client = Client(client_name="Lancelot", user_id=current_user.id)
db.session.add(new_client)
db.session.commit()

或者您可以简单地使用 SQLAlchemy 将客户端附加到您的用户。声明的外键会导致自动分配id:

from flask_security import current_user

new_client = Client(client_name="Sir Bedivere")
current_user.clients.append(new_client)
db.session.commit()