0

I'm trying to create a many-to-many relationship between my three model classes in three separate files: User, Projects and Payments(this is the association class), however I keep receiving this error:

sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'projects.id,' on table 'payments': table 'projects' has no column named 'id,'

After trying to debug for several days I believe my issue is that I don't have a metadata object: "To sort related tables based on their dependencies so that foreign key constraints can be created in the right order." Discussed here: Understanding MetaData() from SQLAlchemy in Python

So how do I setup a metadata object and sort my tables so the foreign key constraints are created in the right order throughout separate files? And if I do so, will it solve the NoReferencedColumnError?

Here are my model classes (error occurs in payment class):

class User(UserMixin, ResourceMixin, db.Model):
    ROLE = OrderedDict([
        ('member', 'Member'),
        ('admin', 'Admin')
    ])

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)

    # Relationships.
    payments = db.relationship(
        'Project', secondary='payments', 
        backref=db.backref('payees', lazy='dynamic')
    )

class Project(ResourceMixin, db.Model):
    __tablename__ = 'projects'
    id = db.Column(db.Integer, primary_key=True)

    # Relationships.
    users = db.relationship('User', secondary="payments")#backref='users')

    fund = db.Column(db.Integer, unique=False, index=True, server_default='0')
    goal = db.Column(db.Integer, nullable=False, server_default='15000')

class Payment(ResourceMixin, db.Model):
    __tablename__ = 'payments'
    id = db.Column(db.Integer, primary_key=True)

    # Payment details.
    user_id = db.Column(db.Integer, db.ForeignKey('users.id',
                                                  onupdate='CASCADE',
                                                  ondelete='CASCADE'),
                        index=True, nullable=False)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id,'))
    amount = db.Column(db.Integer) #Error occurs on this line.

    # Relationships.
    user = db.relationship('User', backref='payments')
    project = db.relationship('Project', backref='payments')
SuperShoot
  • 9,880
  • 2
  • 38
  • 55
koopmac
  • 936
  • 10
  • 27
  • 1
    I think it's just a typo, you declare your `ForeignKey` to the column `'projects.id,'`. Notice that there is a comma _inside_ your quotes. That's why in the error message it says no column named `'id,'` with the comma in the column name. – SuperShoot Mar 22 '19 at 03:55
  • 2
    And in any case, you are already creating a `MetaData` object, that is what inheriting from `db.Model` does for you. Inspect `db.Model.metadata`. – SuperShoot Mar 22 '19 at 03:59

0 Answers0