I'm trying to make an invitation system where one User
has an InvitationToken
that can be sent to multiple invitees
. Each User
can have only one token (one-to-one), as well as be an invitee in multiple tokens (many-to-one).
This is what I have so far:
InvitationToken.py
class InvitationToken(db.Model, SerializeMixin, TimestampMixin):
__tablename__ = "invitation_token"
"""
The relationship to the User model. An InvitationToken can have many Users as invitees.
"""
invitees = db.relationship(
"User", back_populates="invitee_token", foreign_keys="User.invitee_token_id"
)
"""
The relationship to the User model. An InvitationToken can have only one User.
"""
user_id = db.Column(UUID(as_uuid=True), db.ForeignKey("app_user.id"), index=True)
user = db.relationship(
"User",
back_populates="invitation_token",
foreign_keys=[user_id],
uselist=False,
)
User.py
class User(db.Model, TimestampMixin):
__tablename__ = "app_user"
"""
The relationship to the InvitationToken model. A User can have only one InvitationToken.
"""
invitation_token_id = db.Column(
UUID(as_uuid=True), db.ForeignKey("invitation_token.id"), index=True
)
invitation_token = db.relationship(
"InvitationToken",
back_populates="user",
cascade="delete",
foreign_keys=[invitation_token_id],
uselist=False,
)
"""
The relationship to the InvitationToken model. A User can have only one InvitationToken as invitee.
"""
invitee_token_id = db.Column(
UUID(as_uuid=True), db.ForeignKey("invitation_token.id"), index=True
)
invitee_token = db.relationship(
"InvitationToken",
back_populates="invitees",
foreign_keys=[invitee_token_id],
)
I'm getting the following error with my current configuration:
sqlalchemy.exc.ArgumentError: InvitationToken.user and back-reference User.invitation_token are both of the same direction symbol('MANYTOONE'). Did you mean to set remote_side on the many-to-one side ?
What am I missing?
I found a solution, although I do not fully understand it. But it works:
class InvitationToken(db.Model, SerializeMixin, TimestampMixin):
__tablename__ = "invitation_token"
"""
The relationship to the User model. An InvitationToken can have many Users as invitees.
"""
invitees = db.relationship(
"User",
back_populates="invitee_token",
foreign_keys="User.invitee_token_id", # Changed this
)
"""
The relationship to the User model. An InvitationToken can have only one User.
"""
user_id = db.Column(UUID(as_uuid=True), db.ForeignKey("app_user.id"), index=True)
user = db.relationship(
"User",
back_populates="invitation_token",
foreign_keys="User.invitation_token_id", # Changed this
uselist=False,
)
User was left unchanged. This got rid of the error and allowed me to run Flask and have the models behave how I wanted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.