Updated Post models to include like data
Browse files- postly/common/models.py +20 -4
postly/common/models.py
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
-
from dataclasses import dataclass
|
2 |
-
from typing import List
|
3 |
|
4 |
from pydantic import BaseModel
|
5 |
|
@@ -8,6 +8,8 @@ class StrictPost(BaseModel):
|
|
8 |
content: str
|
9 |
timestamp: int
|
10 |
topics: List[str]
|
|
|
|
|
11 |
|
12 |
|
13 |
@dataclass
|
@@ -15,11 +17,25 @@ class Post:
|
|
15 |
content: str
|
16 |
timestamp: int
|
17 |
topics: List[str]
|
|
|
|
|
18 |
|
19 |
|
20 |
if __name__ == "__main__":
|
21 |
# this should be OK, as not strictly typed
|
22 |
-
Post(content=1, timestamp=1, topics=["1"])
|
|
|
|
|
|
|
23 |
|
24 |
# this should result in a validation error, as pydantic enforces strict typing on runtime
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass, field
|
2 |
+
from typing import List, Set
|
3 |
|
4 |
from pydantic import BaseModel
|
5 |
|
|
|
8 |
content: str
|
9 |
timestamp: int
|
10 |
topics: List[str]
|
11 |
+
likes: int = 0
|
12 |
+
liked_by: Set[str] = set()
|
13 |
|
14 |
|
15 |
@dataclass
|
|
|
17 |
content: str
|
18 |
timestamp: int
|
19 |
topics: List[str]
|
20 |
+
likes: int = 0
|
21 |
+
liked_by: Set[str] = field(default_factory=set)
|
22 |
|
23 |
|
24 |
if __name__ == "__main__":
|
25 |
# this should be OK, as not strictly typed
|
26 |
+
post = Post(content="1", timestamp=1, topics=["1"])
|
27 |
+
post.likes += 1
|
28 |
+
post.liked_by.add("user1")
|
29 |
+
print(post)
|
30 |
|
31 |
# this should result in a validation error, as pydantic enforces strict typing on runtime
|
32 |
+
try:
|
33 |
+
strict_post = StrictPost(content=1, timestamp=1, topics=["1"])
|
34 |
+
except Exception as e:
|
35 |
+
print(f"Validation error: {e}")
|
36 |
+
|
37 |
+
# this should be OK, as strictly typed
|
38 |
+
strict_post = StrictPost(content="1", timestamp=1, topics=["1"])
|
39 |
+
strict_post.likes += 1
|
40 |
+
strict_post.liked_by.add("user1")
|
41 |
+
print(strict_post)
|