Flask-SQLAlchemy Error - AttributeError: 'NoneType' object has no attribute 'append'

Flask-SQLAlchemy Error - AttributeError: 'NoneType' object has no attribute 'append'

下面我为包含公司的 table 和包含合同的 table 定义了 SQLAlchemy 模型。每个公司可以有很多合同,而每个合同可以属于一个公司(一对多关系)。此关系由 contracts = db.relationship('ContractModel', backref=db.backref('company', lazy=True)).

建模

型号:

   class CompanyModel(db.Model):
       id = db.Column(db.Integer, primary_key=True)
       name = db.Column(db.String(64), unique=True, nullable=False)
       industry = db.Column(db.String(64), nullable=False)
       password = db.Column(db.String(64), nullable=False)
       company_logo_path = db.Column(db.String(255), unique=True, nullable=False)

       contracts = db.relationship('ContractModel', backref=db.backref('company', lazy=True))
   
   class ContractModel(db.Model):
       id = db.Column(db.Integer, primary_key=True) 
       length = db.Column(db.Integer, nullable=False)
       value = db.Column(db.Float, nullable=False)
       description = db.Column(db.Text, nullable=False)
       location = db.Column(db.String(50), nullable=False)
       date = db.Column(db.Date, nullable=False)
       company_name = db.Column(db.String, db.ForeignKey(CompanyModel.name), nullable=False)
       status = db.Column(db.Boolean, default=True, nullable=False)

我尝试在创建合同后将公司附加到合同(链接它们):

    contract = ContractModel(length=args['contract_length'], value=args['contract_value'], 
                                description=args['contract_description'], location=args['contract_location'], 
                                status=args['contract_status'], date=datetime.utcnow(), company_name=args['company_name'])
    
    associated_company = CompanyModel.query.filter_by(name=args['company_name']).first() # Company name resides in args['company_name']. This company has already been added to the database.
    contract.company.append(associated_company)

这给出了错误:AttributeError: 'NoneType' object has no attribute 'append',其中罪魁祸首是:contract.company.append(associated_company)。为什么即使定义了一对多关系,我也无法将公司附加到合同中?我是否错误地建立了关系模型?

你的关系是正确的。唯一的问题是 contract.company 当前是 newly-created ContractModel 对象的未定义属性。然后您试图将另一个对象附加到此 'NoneType'。指定与哪家公司签订 link 合同的正确方法是修改 contract.company 属性而不是添加它。如果您在创建新合约之前定义 associated_company,您甚至可以分两行执行此操作:

associated_company = CompanyModel.query.filter_by(name=args['company_name']).first()

contract = ContractModel(length=args['contract_length'], value=args['contract_value'], 
                                description=args['contract_description'], location=args['contract_location'], 
                                status=args['contract_status'], date=datetime.utcnow(), company_name=args['company_name'], 
                                company=associated_company)