Skip to content

Commit 3eb3e41

Browse files
committed
update: add PermissionMixin to db/base.py to automatically create a polymorphic One-to-Many relationship to the Permission table.
1 parent d6466f9 commit 3eb3e41

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

db/base.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
- `ReleaseMixin`: Adds a release status column referencing the `lexicon_term` table.
3030
- `AuditMixin`: Adds standard audit columns (created_at, created_by, updated_at, updated_by).
3131
5. A simple `User` model for tracking user information in audit columns.
32-
6. Polymorphic helper mixins (`StatusHistoryMixin`, `NotesMixin`, `AttributionMixin`, etc.)
32+
6. Polymorphic helper mixins (`StatusHistoryMixin`, `NotesMixin`, `AttributionMixin`, `PermissionMixin`.)
3333
which provide a clean, reusable way to add relationships to the polymorphic
3434
metadata tables. Any model that can have a status history (like Thing or Location)
3535
can simply inherit from the `StatusHistoryMixin` mixin.
@@ -191,6 +191,25 @@ def status_history(self):
191191
)
192192

193193

194+
class PermissionMixin:
195+
"""
196+
Mixin for models that can have permissions (e.g., Thing, Location).
197+
It automatically creates a polymorphic One-to-Many relationship to the
198+
Permission table.
199+
"""
200+
201+
@declared_attr
202+
def permissions(self):
203+
# One-to-Many polymorphic relationship
204+
return relationship(
205+
"Permission",
206+
primaryjoin=f"and_({self.__name__}.{self.__name__.lower()}_id==Permission.permissible_id, "
207+
f"Permission.permissible_type=='{self.__name__}')",
208+
lazy="selectin",
209+
viewonly=True,
210+
)
211+
212+
194213
class User(Base):
195214
"""Represents a user in the system."""
196215

0 commit comments

Comments
 (0)