python-Flask-Sqlalchemy,多对多关系中的辅助表的主键
作者:互联网
我正在尝试使用Flask-Sqlalchemy为Postgresql数据库建立简单的多对多关系:
from app import db
from sqlalchemy.dialects.postgresql import UUID
authors_books = db.Table(
'authors_books',
db.Column('id', UUID(as_uuid=True), primary_key=True),
db.Column('author_id', UUID(as_uuid=True), db.ForeignKey('authors.id')),
db.Column('book_id', UUID(as_uuid=True), db.ForeignKey('books.id')),
)
class Author(db.Model):
__tablename__ = 'authors'
# Fields
id = db.Column(UUID(as_uuid=True), primary_key=True)
first_name = db.Column(db.String)
last_name = db.Column(db.String)
# Relationships
books = db.relationship('Book',
secondary=authors_books,
backref=db.backref('authors', lazy='dynamic'))
class Book(db.Model):
__tablename__ = 'books'
id = db.Column(UUID(as_uuid=True), primary_key=True)
title = db.Column(db.String)
如果我尝试将书添加到作者的书清单中:
u = User.query.get(user_id)
b = Book.query.get(book_id)
u.books.append(b)
所以我有这个错误:
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, "d5fb5e3f-2082-41f5-bcd2-bfdde11c78d4", "058fdbbd-d49f-4626-b669-b48dc4e75203").
[SQL: 'INSERT INTO authors_books (author_id, book_id) VALUES (%(author_id)s, %(book_id)s) RETURNING authors_books.id']
[parameters: {'author_id': UUID('d5fb5e3f-2082-41f5-bcd2-bfdde11c78d4'), 'book_id': UUID('058fdbbd-d49f-4626-b669-b48dc4e75203')}]
// Werkzeug Debugger
有没有办法配置用于自动在关联表中设置主键的模型?
解决方法:
https://groups.google.com/forum/#!topic/sqlalchemy/WAHaPIuzqZQ
authors_books = db.Table(
'authors_books',
db.Column('id', UUID(as_uuid=True), primary_key=True, default=lambda: uuid.uuid4().hex),
db.Column('author_id', UUID(as_uuid=True), db.ForeignKey('authors.id')),
db.Column('book_id', UUID(as_uuid=True), db.ForeignKey('books.id')),
)
标签:postgresql,sqlalchemy,many-to-many,flask,python 来源: https://codeday.me/bug/20191120/2042876.html