0

I'm new in Flask and especially with SQLAlchemy concept. I have two models which call User and Message:

@dataclass
class User(UserMixin, db.Model):
    __tablename__ = 'user'
    id: int
    email: str
    password: str
    name: str

    id = Column(Integer, primary_key=True)
    email = Column(String(100), unique=True)
    password = Column(String(100))
    name = Column(String(100))


@dataclass
class Message(db.Model):
    __tablename__ = 'message'
    id: int
    sender: int
    receiver: int
    message: str
    creation_date: datetime
    did_read: bool


    id = Column(Integer, primary_key=True)
    sender = Column(Integer, ForeignKey('user.id'), nullable=False)
    receiver = Column(Integer, ForeignKey('user.id'), nullable=False)
    message = Column(String(200), nullable=False)
    creation_date = Column(DateTime, default=datetime.utcnow)
    did_read = Column(Boolean, default=False)

sender and receiver in Message model should hold the id of a correct user.
And, for example, when I try to send a messege from user with id=1 (which is in the database) to user with id=2 (which is not in the database yet) it allows me to send it anyway and is not make sense since user with id=2 is not in the database.
I want that it will raise an error and notify me that the user doesn't exist.
What should I do?

Thanks!

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • What database are you using? I think SqlAlchemy depends on the database to enforce this constraint. – Barmar Nov 20 '21 at 23:19
  • 1
    If you're using SQLite: https://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys – Ilja Everilä Nov 20 '21 at 23:47
  • what meas `send` ? Do you have some function to send message ? How do you use database for sending message? Maybe problem is this function, not in database. – furas Nov 21 '21 at 01:07

0 Answers0