我有几个课程:
import uuid
from app import db, create_app
from sqlalchemy.sql import func
from sqlalchemy.dialects.postgresql import UUID, ARRAY, JSONB
class Ticket(db.Model):
__tablename__ = 'tickets'
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
time = db.Column(db.DateTime, server_default=func.now(), index=True)
proposed_names = db.Column(ARRAY(db.String))
measurements = db.relationship('TempMeasurement', back_populates='ticket')
class BaseMeasurement(object):
id = db.Column(db.Integer, primary_key=True)
@declared_attr
def type_id(self):
return db.Column(db.Integer, db.ForeignKey('optical_data_types.id'))
@declared_attr
def type(self):
return db.relationship('OpticalDataType')
@declared_attr
def operator_id(self):
return db.Column(db.Integer, db.ForeignKey('operators.id'))
@declared_attr
def operator(self):
return db.relationship('Operator')
@declared_attr
def item_id(self):
return db.Column(db.String, db.ForeignKey('items.serial'))
@declared_attr
def item(self):
return db.relationship('Item')
time = db.Column(db.DateTime, index=True)
instrument = db.Column(db.String)
instrument_sn = db.Column(db.String)
data = db.Column(JSONB)
class TempMeasurement(db.Model, BaseMeasurement):
__tablename__ = 'ticket_data'
id = db.Column(db.Integer, primary_key=True)
ticket_id = db.Column(UUID(as_uuid=True), db.ForeignKey('tickets.id'), index=True)
ticket = db.relationship('Ticket', back_populates='measurements')
original_paths = db.Column(ARRAY(db.String))
我想要/期望的是我可以使用多个子Ticket
创建TempMeasurements
并将其提交到数据库。类似的东西:
app = create_app()
with app.app_context():
ticket = Ticket()
ticket.measurements = [TempMeasurement(...)]
db.session.add(ticket) # <-- error on this line
db.session.commit()
但是,我在SQLAlchemy中得到了一个模糊的错误:
AttributeError: 'str' object has no attribute '_sa_instance_state'
完整跟踪here。
我认为可能是因为UUID
ticket_id列有as_uuid,所以我把它简单地设为UUID(隐式地为str
),但这并没有解决我的问题。
SQLAlchemy中的错误太深,让我无法理解 - 有人可以帮忙吗?