-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmodels.py
More file actions
77 lines (59 loc) · 2.31 KB
/
models.py
File metadata and controls
77 lines (59 loc) · 2.31 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Models that implement sections
"""
from typing import NewType, TypeAlias, cast, override
from django.core.exceptions import ValidationError
from django.db import models
from ..containers.api import get_container_subclass_of
from ..containers.models import Container, ContainerPK, ContainerVersion
from ..publishing.models import PublishableEntity
from ..subsections.models import Subsection
__all__ = [
"Section",
"SectionVersion",
]
SectionPK = NewType("SectionPK", ContainerPK)
@Container.register_subclass
class Section(Container):
"""
A Section is type of Container that holds Subsections.
Via Container and its PublishableEntityMixin, Sections are also publishable
entities and can be added to other containers.
"""
PK: TypeAlias = SectionPK
type_code = "section"
olx_tag_name = "chapter" # Serializes to OLX as `<chapter>...</chapter>`.
container = models.OneToOneField(
Container,
on_delete=models.CASCADE,
parent_link=True,
primary_key=True,
)
@property
def id(self) -> SectionPK:
return cast(SectionPK, self.publishable_entity_id)
@override
@classmethod
def validate_entity(cls, entity: PublishableEntity) -> None:
"""Check if the given entity is allowed as a child of a Section"""
# Sections only allow Subsections as children, so the entity must be 1:1 with Container:
if not hasattr(entity, "container"):
raise ValidationError("Only Units can be added as children of a Subsection (found non-Container child)")
if get_container_subclass_of(entity.container) is not Subsection:
raise ValidationError("Only Subsection can be added as children of a Section")
class SectionVersion(ContainerVersion):
"""
A SectionVersion is a specific version of a Section.
Via ContainerVersion and its EntityList, it defines the list of Subsections
in this version of the Section.
"""
container_version = models.OneToOneField(
ContainerVersion,
on_delete=models.CASCADE,
parent_link=True,
primary_key=True,
)
@property
def section(self) -> Section:
"""Convenience accessor to the Section this version is associated with"""
return self.container_version.container.section # pylint: disable=no-member