【问题标题】:Unidrectional OneToOne relationship SqlAlchemy in PythonPython中的单向一对一关系SqlAlchemy
【发布时间】:2020-11-21 17:41:26
【问题描述】:

我正在尝试在 SqlAlchemy 中建立 OneToOne 关系,其中孩子的表 ID 已经是外键,但它抛出了错误:

sqlalchemy.orm.exc.DetachedInstanceError: Instance <Vetor at 0x7fcc81307070> is not bound to a Session; attribute refresh operation cannot proceed

下面,两个模型和服务..

class CUBE(types.UserDefinedType):
 def get_col_spec(self, **kw):
   return "CUBE"

class Vetor(db.Model):
   id = db.Column(db.Integer, primary_key=True)
   data = db.Column(db.DateTime(), default=db.func.now())
   vetor = db.Column(CUBE)
   sistema_origem_id = db.Column(db.Integer)
   
   def __init__(self, vetor, sistema_origem):
       self.vetor = vetor
       self.sistema_origem_id = sistema_origem
       
   def __repr__(self):
       return "<Vetor(id='%s', data='%s', vetor='%s', sistema_origem_id='%s')>" % (self.id, self.data, self.vetor, self.sistema_origem_id)

class FBinary(db.Model):
    id = db.Column(db.Integer, db.ForeignKey("vetor.id"), primary_key=True)
    binario = db.Column(db.LargeBinary)
    contenttype = db.Column(db.String())

    def __init__(self, id, binario, contenttype):
        self.id = id
        self.binario = binario
        self.contenttype = contenttype
    
    def __repr__(self):
        return "<FBinary(id='%s', binario='%s', contentype='%s')>" % (self.id, self.binario, self.contenttype)

试图同时提交的类:

    ....code.....

    face = Vetor(vetor, 1 ) 
    db.session.add(face)

    binario = FBinary(id=face, binario=foto_bytes, contenttype='')
    db.session.add(binario)

    db.session.commit()

【问题讨论】:

    标签: python flask sqlalchemy foreign-keys one-to-one


    【解决方案1】:

    我无法重现您的错误。话虽如此,一个可能的解决方案应该是:

        face = Vetor(vetor, 1 ) 
        db.session.add(face)
        db.session.comit()  # Now your database has an entry in Table vetor with id 1
    
        binario = FBinary(id=face.id, binario=foto_bytes, contenttype='')  # reference the id from your face object.
        db.session.add(binario)
        db.session.commit()
    

    我假设 vetor 是某种数据并且不是 Vetor 对象(为什么要尝试将 Vetor 对象保存在 vetor 表中?)。

    希望对您有所帮助。请考虑在您的下一个问题中提供minimal reproducible example

    【讨论】:

    • 您好,感谢您的评论。用于人脸识别。我正在使用这个 API pypi.org/project/face-recognition,这将是“注册面”API。我需要将数据保存在“CUBE”列(PG 扩展名)中。 (人脸识别时比较比较好,可以通过查询进行比较)。 “vetor”是生物特征数据,类似于(-0.137929931282997131, 0.0440808013081550598, 0.0179916676133871178,....)。但这不是问题,如果我不将二进制文件添加到会话中db.session.add(binario),我可以毫无问题地保存面子
    • 按照你说的做这不是理想的,因为我必须提交 Face(Vetor 表),并且会有许多其他相关的关系,如果出现问题我需要回滚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2020-11-01
    • 2014-03-06
    • 1970-01-01
    • 2016-06-15
    • 2021-08-31
    相关资源
    最近更新 更多