我正在创建一个网络应用程序,它可以记录笔记并将其存储在数据库中。我正在使用 MySQL 数据库。
运行代码时,我收到错误。
我认为这个错误是在我的
models.py
这是错误:
sqlalchemy.exc.ArgumentError: Error creating backref 'user_notes' on relationship 'Note.note_author': property of that name exists on mapper 'Mapper[User(users)]'
我有两个文件,这是两个文件:
模型.py
from sqlalchemy import Column, Integer, String, UniqueConstraint, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Note(Base):
__tablename__ = 'notes'
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(100), nullable=False)
content = Column(String(1000), nullable=False)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
note_author = relationship('User', backref='user_notes')
def __repr__(self):
return f'<Note(id={self.id}, title={self.title}, content={self.content}, user={self.user.username})>'
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False, unique=True)
email = Column(String(100), nullable=False, unique=True)
password = Column(String(100), nullable=False)
user_notes = relationship('Note', backref='note_author')
def __repr__(self):
return f'<User(id={self.id}, username={self.username}, email={self.email})>'
还有第二个
app.py
from flask import Flask, render_template, request, redirect, url_for
from sqlalchemy import create_engine
from flask_mysqldb import MySQL
from sqlalchemy.orm import sessionmaker
from models import Base, Note, User
# create Flask app
app = Flask(__name__)
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'notes_db'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
# create database engine and session
engine = create_engine('mysql+pymysql://user:password@localhost/mydatabase')
Base.metadata.bind = engine
Session = sessionmaker(bind=engine)
session = Session()
@app.route('/')
def index():
# get all notes
notes = session.query(Note).all()
# get note author
for note in notes:
note_author = note.note_author
# get count of total notes
note_count = session.query(note_author).count()
# render template with notes and count
return render_template('index.html', notes=note_author, note_count=note_count)
@app.route('/create-note', methods=['GET', 'POST'])
def create_note():
if request.method == 'POST':
# get form data
title = request.form['title']
content = request.form['content']
user_id = int(request.form['user_id'])
user = session.query(User).get(user_id)
# create new note
new_note = Note(title=title, content=content, author=user)
session.add(new_note)
session.commit()
# get user notes
user_notes = User.user_notes
# redirect to homepage
return redirect(url_for('index'))
else:
# get all users
users = session.query(User).all()
# render form template
return render_template('create_note.html', users=users)
@app.route('/edit-note/<int:id>', methods=['GET', 'POST'])
def edit_note(id):
# get note by id
note = session.query(Note).filter_by(id=id).first()
if request.method == 'POST':
# update note
note.title = request.form['title']
note.content = request.form['content']
note.user_id = int(request.form['user_id'])
session.commit()
# redirect to homepage
return redirect(url_for('index'))
else:
# get all users
users = session.query(User).all()
# render form template with note and users
return render_template('edit_note.html', note=note, users=users)
@app.route('/delete-note/<int:id>')
def delete_note(id):
# get note by id
note = session.query(Note).filter_by(id=id).first()
# delete note
session.delete(note)
session.commit()
# redirect to homepage
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
如何解决我遇到的这个错误?
backref
关键字会自动在相关模型上创建关系,但由于您在两个模型上都创建了关系,因此会引发错误。相反,在两个模型上使用 back_populates
关键字:
class Note(Base):
note_author = relationship('User', back_populates='user_notes')
class User(Base):
user_notes = relationship('Note', back_populates='note_author')