'Relationship between 3 table class in python, flask and sqlalchemy
I am using Python 3.10 and SQLAlchemy 1.4.29
It has 3 classes User, Post and Comment. A User has many Post instances (1-N relationship).
And the hard part is creating the relationship between the post comments and the post, as I need to add the user in the relationship to identify the comment.
Below is the models.py code and the error that is appearing.
error:
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to
initialize - can't proceed with initialization of other mappers.
Triggering mapper: 'mapped class Post->post'.
Original exception was:
Error creating backref 'comentarios_do_post' on relationship
'Post.comentarios': property of that name exists on mapper 'mapped
class Comentario->comentario'
code:
from main import database
from datetime import datetime
class Usuario(database.Model):
id = database.Column(database.Integer, primary_key=True)
username = database.Column(database.String, nullable=False)
email = database.Column(database.String, nullable=False, unique=True)
senha = database.Column(database.String, nullable=False)
foto_perfil = database.Column(database.String, default='default.jpg')
posts = database.relationship('Post', backref='autor', lazy=True)
comentarios = database.relationship('Comentario', backref='autor_do_comentario', lazy=True)
class Post(database.Model):
id = database.Column(database.Integer, primary_key=True)
titulo = database.Column(database.String, nullable=False)
corpo = database.Column(database.Text, nullable=False)
data_criacao = database.Column(database.DateTime, nullable=False, default=datetime.utcnow())
like = database.Column(database.Integer, default='0')
deslike = database.Column(database.Integer, default='0')
id_usuario = database.Column(database.Integer, database.ForeignKey('usuario.id'), nullable=False)
comentarios = database.relationship('Comentario', backref='comentarios_do_post', lazy=True)
class Comentario(database.Model):
id = database.Column(database.Integer, primary_key=True)
corpo = database.Column(database.Text, nullable=False)
data_criacao = database.Column(database.DateTime, nullable=False, default=datetime.utcnow())
id_post = database.Column(database.Integer, database.ForeignKey('post.id'), nullable=False)
id_usuario = database.Column(database.Integer, database.ForeignKey('usuario.id'), nullable=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
