sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'title.id' on table 'post'
Asked Answered
K

1

6

I getting this error:

sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'title.id' on table 'post': table 'title' has no column named 'id'

when I remove these two line I'm not getting any error:

head_id = Column(Integer, ForeignKey('title.id'))

head = relationship('Title', backref='post')

What I'm doing wrong with relationship and foreignKey?

My code main.py

from flask import Flask, render_template, request, redirect, url_for
import datetime
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, String, Integer, create_engine, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship


# flask documentation >> https://flask.palletsprojects.com/en/1.1.x/quickstart/
app = Flask(__name__, template_folder='template', static_folder='static')

Base = declarative_base()

date = datetime.datetime.strftime(datetime.datetime.now(), '%d-%b-%Y')

engine = create_engine('mysql://root:@localhost/flask')
Base.metadata.create_all = engine

database = sessionmaker(bind=engine)
session = database()



class contacts(Base):
    __tablename__='contacts'
    id = Column('No.', Integer, primary_key=True)
    name = Column('Name', String(15), nullable=True)
    email = Column('Email', String(20), nullable=True)
    phone = Column('Phone', String(14), nullable=True)
    message = Column('Message', String(100))
    date = Column('Date', String, default=date)
    def __repr__(self):
        return '<contacts(Name=%s, Email=%s, Phone=%s, Message=%s, Date=%s)>' % (
            self.name, self.email, self.phone, self.message, self.date)



class Title(Base):
    __tablename__='title'
    id = Column('No', Integer, primary_key=True)
    title = Column('Title', String, nullable=False)
    date = Column('Date', String, nullable=False, default=date)
    def __repr__(self):
        return '<head(Title=%s, Date=%s)>' % (self.title, self.date)

class Post(Base):
    __tablename__='post'
    id = Column('No', Integer, primary_key=True)
    post = Column('Post', String, nullable=False)
    head_id = Column(Integer, ForeignKey('title.id'))
    head = relationship('Title', backref='post')
    def __repr__(self):
        return '<post(Post=%s)>' % self.post

@app.route('/')
def index():
    data = session.query(Post).all()
    return render_template('index.html', data=data)


# router for contact ['post' and 'get'] method
@app.route('/contact', methods=['POST', 'GET'])
def contact():
    # if 'contact.html' form method is 'post' this will run , otherwise not
    if request.method=='POST':
        # getting value from your 'contact.html' page
        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']
        message = request.form['message']

        # attempt to adding value in database
        try:
            # commit to adding value in database
            value = contacts(name=name, email=email, phone=phone, message=message)
            session.add(value)
            session.commit()
            session.close()

            # redirect home page
            return redirect(url_for('index'))

        # any problem while adding value in database
        except Exception as e:
            print(e)
    else:
        # not request for 'POST'
        return render_template('contact.html')

# These are all route points (end points)
@app.route('/post')
def post():
    return render_template('post.html')


@app.route('/about')
def about():
    return render_template('about.html')




if __name__ == '__main__':
    # run application, and  'debug'= It'll auto configure you changes (you don't need you restart you app again and again'
    app.run(debug=True)

How can I create relationship b/w Title and Post?

Kulak answered 29/9, 2019 at 4:26 Comment(0)
I
0

In the foreign key declaration ForeignKey('title.id'), id refers to the name of the column in the database. However, the declaration of the Title model's id attribute looks like this:

id = Column('No', Integer, primary_key=True)

The first argument, 'No', is the name of the column in the database*; this doesn't match the foreign key declaration, so an exception is raised by the mapper because there is no column in the database table named 'id'.

There are two possible solutions:

  1. Map the foreign key to 'title.No'
  2. Remove the 'No' argument in the declaration of Title.id (it will default to 'id') or change it to 'id'.

* The ORM allows having model attribute names that are different from the column name in the mapped database table, but we must take care to understand when we are referencing attributes and when we are referencing column names, as in this case.

Infiltrate answered 19/12, 2023 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.