首页 > 解决方案 > 'NoneType' 对象没有属性 'name' - 当模型之间建立通信时。Flask

问题描述

在我的应用程序中,我使用了两个模型,它们之间是一对一的:

relationship:db.relationship('Operation',uselist=False, backref='operat')

以下是模型本身。

class Operation(db.Model):
    __tablename__ = "operation"
    id = db.Column(db.Integer, primary_key=True)    
    date_operation = db.Column(db.DateTime, index=True)
    code = db.Column(db.Integer, index=True)
    status_id = db.Column(db.Integer)
    status = db.Column(db.String(60))
    type_id = db.Column(db.Integer)
    type = db.Column(db.String(120))
    storage_id = db.Column(db.Integer)
    storage = db.Column(db.String(240))
    contragent_id = db.Column(db.Integer, db.ForeignKey('contragent.id'))
    contragent = db.Column(db.String(240))
    sum_operation = db.Column(db.Integer)
    rezerv = db.Column(db.Integer)
    cnt_doc = db.Column(db.Integer)
    stellag = db.Column(db.Integer)

    def __repr__(self):
        return '<Operation {}>'.format(self.code)


class Contragent(db.Model):
    __tablename__ = "contragent"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(360))
    code = db.Column(db.Integer, index=True)
    adress = db.Column(db.String(480))
    inn = db.Column(db.Integer)
    operations = db.relationship('Operation',uselist=False, backref='operat')


    def __repr__(self):
        return '<Contragent {}>'.format(self.name)  

选择记录并将记录名称获取到引用模型时p.operat.name

>>> o = Operation.query.all()
>>> for p in o:
...     print(p.id, p.operat.name, p.code)
...
2 Рога и копытца22sdsd 222

我得到错误:

Traceback (most recent call last):
  File "<console>", line 2, in <module>
AttributeError: 'NoneType' object has no attribute 'name'
>>>

是什么导致了错误以及如何修复它?

标签: pythonflasksqlalchemy

解决方案


推荐阅读