gpt4 book ai didi

postgresql - 为关系表设置 server_default 值

转载 作者:行者123 更新时间:2023-11-29 11:35:03 25 4
gpt4 key购买 nike

我有两个管理员和角色表,通过第三个表 assignments(多对多关系)与字段 role_idadministrator_id 和一些额外的字段 created_atupdated_at,我想自动填充它们:

assignments = db.Table('assignments',
db.Column('role_id', db.Integer, db.ForeignKey('roles.id')),
db.Column('administrator_id', db.Integer,
db.ForeignKey('administrators.id')),
db.Column('created_at', db.DateTime, server_default=db.func.now()),
db.Column('updated_at', db.DateTime, server_default=db.func.now(),
onupdate=db.func.now()),
db.ForeignKeyConstraint(['administrator_id'], ['administrators.id']),
db.ForeignKeyConstraint(['role_id'], ['roles.id'])
)

class Administrator(db.Model, UserMixin):
__tablename__ = 'administrators'

id = Column(Integer, primary_key=True, server_default=text("nextval('administrators_id_seq'::regclass)"))
email = Column(String(255), nullable=False, unique=True, server_default=text("''::character varying"))
name = Column(String(255))
surname = Column(String(255))

roles = db.relationship('Role', secondary=assignments,
backref=db.backref('users', lazy='dynamic'))


class Role(db.Model):
__tablename__ = 'roles'

id = Column(Integer, primary_key=True, server_default=text("nextval('roles_id_seq'::regclass)"))
name = Column(String(255))

但是当我将角色分配给管理员时

admin.roles = [role1]
db.session.add(admin)
db.session.commit()

它因以下错误而中断:

IntegrityError: (psycopg2.IntegrityError) null value in column "created_at" violates not-null constraint
DETAIL: Failing row contains (1265, 19, 3, null, null).
[SQL: 'INSERT INTO assignments (role_id, administrator_id) VALUES (%(role_id)s, %(administrator_id)s)'] [parameters: {'administrator_id': 19, 'role_id': 3}]

有什么方法可以为 assignments 表中的 created_atupdated_at 字段设置默认值?

最佳答案

它使用 defaultonupdate 参数而不是 server_defaultserver_onupdate 工作:

db.Column('created_at', db.DateTime, default=db.func.now()),
db.Column('updated_at', db.DateTime, default=db.func.now(),
onupdate=db.func.now()),

关于postgresql - 为关系表设置 server_default 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36294819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com