sqlalchemy.exc.NoReferencedColumnError:无法初始化表“post”上的外键“title.id”的目标列

问题描述 投票:0回答:1

我收到此错误:

sqlalchemy.exc.NoReferencedColumnError:无法初始化表“post”上的外键“title.id”的目标列:表“title”没有名为“id”的列

当我删除这两行时,我没有收到任何错误:

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

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

我对

relationship
foreignKey
做错了什么?

我的代码

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)

如何建立黑白关系

Title
Post

mysql python-3.x flask flask-sqlalchemy
1个回答
0
投票

在外键声明中

ForeignKey('title.id')
id
指的是数据库中列的名称。但是,
Title
模型的
id
属性的声明如下所示:

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

第一个参数

'No'
是数据库中列的名称*;这与外键声明不匹配,因此映射器会引发异常。

有两种可能的解决方案:

  1. 将外键映射到
    'title.No'
  2. 删除
    'No'
    声明中的
    Title.id
    参数(默认为
    'id'
    )或将其更改为
    'id'

* ORM 允许模型属性名称与映射数据库表中的列名称不同,但我们必须注意理解何时引用属性以及何时引用列名称,就像在本例中一样。

© www.soinside.com 2019 - 2024. All rights reserved.