File size: 2,194 Bytes
b4f2238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
QuerySet 预加载管理器

为核心 Model 提供带预加载配置的查询集工厂方法,
消除各 Service 中重复的 select_related/prefetch_related 定义。
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from django.db.models import QuerySet


class CaseQuerySetManager:
    """案件查询集管理器"""

    SELECT_RELATED: tuple[str, ...] = ("contract",)
    PREFETCH_RELATED: tuple[str, ...] = (
        "parties__client",
        "assignments__lawyer",
        "assignments__lawyer__law_firm",
        "logs__attachments",
        "case_numbers",
        "supervising_authorities",
        "contract__supplementary_agreements__parties__client",
    )

    @classmethod
    def with_standard_prefetch(cls) -> QuerySet[Any, Any]:
        """返回带标准预加载的查询集"""
        from django.apps import apps
        from django.db.models import QuerySet as QS

        Case = apps.get_model("cases", "Case")
        qs: QS[Any] = Case.objects.select_related(*cls.SELECT_RELATED).prefetch_related(*cls.PREFETCH_RELATED)
        return qs

    @classmethod
    def with_extra_prefetch(cls, *extra: str) -> QuerySet[Any, Any]:
        """返回带额外预加载的查询集"""
        return cls.with_standard_prefetch().prefetch_related(*extra)


class ContractQuerySetManager:
    """合同查询集管理器"""

    PREFETCH_RELATED: tuple[str, ...] = (
        "cases",
        "contract_parties__client",
        "payments",
        "reminders",
        "assignments__lawyer",
        "assignments__lawyer__law_firm",
    )

    @classmethod
    def with_standard_prefetch(cls) -> QuerySet[Any, Any]:
        """返回带标准预加载的查询集"""
        from django.apps import apps
        from django.db.models import QuerySet as QS

        Contract = apps.get_model("contracts", "Contract")
        qs: QS[Any] = Contract.objects.prefetch_related(*cls.PREFETCH_RELATED)
        return qs

    @classmethod
    def with_extra_prefetch(cls, *extra: str) -> QuerySet[Any, Any]:
        """返回带额外预加载的查询集"""
        return cls.with_standard_prefetch().prefetch_related(*extra)