Skip to content
Advertisement

Flask-SQLAlchemy Error – AttributeError: ‘NoneType’ object has no attribute ‘append’

Below I have defined SQLAlchemy models for a table containing companies and a table containing contracts. Each company can have many contracts while each contract can belong to one company (one to many relationship). This relationship is modelled by contracts = db.relationship('ContractModel', backref=db.backref('company', lazy=True)).

Models:

JavaScript

I try to append a company to a contract (which links them) after creating a contract:

JavaScript

This gives the error: AttributeError: 'NoneType' object has no attribute 'append' where the culprit line is: contract.company.append(associated_company). Why am I not able to append a company to a contract even though their one to many relationship is defined? Did I model the relationship incorrectly?

Advertisement

Answer

Your relationship is correct. The only problem is that contract.company is currently an undefined attribute of your newly-created ContractModel object. You are then trying to append another object to this ‘NoneType’. The correct way to specify which company with which to link a contract would be by modifying the contract.company attribute instead of adding to it. You could even do this in two lines if you define associated_company before creating a new contract:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement