-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
39 lines (28 loc) 路 1.72 KB
/
Copy pathmodels.py
File metadata and controls
39 lines (28 loc) 路 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from __future__ import annotations # forward reference support for python versions older than 3.14
from datetime import UTC, datetime
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from database import Base
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
username: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
email: Mapped[str] = mapped_column(String(120), unique=True, nullable=False)
password_hash : Mapped[str] = mapped_column(String(200), nullable=False)
image_file: Mapped[str|None] = mapped_column(String(200), nullable=True, default=None)
posts: Mapped[list[Post]] = relationship(back_populates="author", cascade="all, delete-orphan")
@property
def image_path(self) -> str:
if self.image_file:
return f"/media/profile_pics/{self.image_file}"
return f"/static/profile_pics/default.jpg"
class Post(Base):
__tablename__ = 'posts'
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
title: Mapped[str] = mapped_column(String(100), nullable=False)
content: Mapped[str] = mapped_column(Text, nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True)
date_posted: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
author: Mapped[User] = relationship(back_populates="posts")
likes: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
# server_defaults exists because database usually tries to put null value to a new column of existing table.