• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

barseghyanartur / django-rest-framework-tricks / 3680627646

pending completion
3680627646

push

github

Artur Barseghyan
Up docs

170 of 190 relevant lines covered (89.47%)

4.47 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

100.0
/src/rest_framework_tricks/models/fields/nested_proxy.py
1
"""
2
Nested proxy field.
3
"""
4
from ...utils import DictProxy
5✔
5

6
__author__ = "Artur Barseghyan <artur.barseghyan@gmail.com>"
5✔
7
__copyright__ = "2017-2022 Artur Barseghyan"
5✔
8
__license__ = "GPL-2.0-only OR LGPL-2.1-or-later"
5✔
9
__all__ = ("NestedProxyField",)
5✔
10

11

12
def NestedProxyField(*fields, **options):
5✔
13
    """NestedProxyField field.
14

15
    Example:
16

17
        >>> from django.db import models
18
        >>> from rest_framework_tricks.models.fields import NestedProxyField
19
        >>> from .constants import BOOK_STATUS_CHOICES, BOOK_STATUS_DEFAULT
20
        >>>
21
        >>>
22
        >>> class Book(models.Model):
23
        >>>
24
        >>>     title = models.CharField(max_length=100)
25
        >>>     description = models.TextField(null=True, blank=True)
26
        >>>     summary = models.TextField(null=True, blank=True)
27
        >>>     publication_date = models.DateField()
28
        >>>     state = models.CharField(max_length=100,
29
        >>>                              choices=BOOK_STATUS_CHOICES,
30
        >>>                              default=BOOK_STATUS_DEFAULT)
31
        >>>     isbn = models.CharField(max_length=100, unique=True)
32
        >>>     price = models.DecimalField(max_digits=10, decimal_places=2)
33
        >>>     pages = models.PositiveIntegerField(default=200)
34
        >>>     stock_count = models.PositiveIntegerField(default=30)
35
        >>>
36
        >>>     # This does not cause a model change
37
        >>>     publishing_information = NestedProxyField(
38
        >>>         'publication_date',
39
        >>>         'isbn',
40
        >>>         'pages',
41
        >>>     )
42
        >>>
43
        >>>     # This does not cause a model change
44
        >>>     stock_information = NestedProxyField(
45
        >>>         'stock_count',
46
        >>>         'price',
47
        >>>         'state',
48
        >>>     )
49
        >>>
50
        >>>     class Meta:
51
        >>>
52
        >>>         ordering = ["isbn"]
53
        >>>
54
        >>>     def __str__(self):
55
        >>>         return self.title
56

57
    Nesting depth is unlimited, so the following would be possible as well.
58

59
    Example:
60

61
        >>> class Author(models.Model):
62
        >>>
63
        >>>     salutation = models.CharField(max_length=10)
64
        >>>     name = models.CharField(max_length=200)
65
        >>>     email = models.EmailField()
66
        >>>     birth_date = models.DateField(null=True, blank=True)
67
        >>>     biography = models.TextField(null=True, blank=True)
68
        >>>     phone_number = models.CharField(max_length=200,
69
        >>>                                     null=True,
70
        >>>                                     blank=True)
71
        >>>     website = models.URLField(null=True, blank=True)
72
        >>>     company = models.CharField(max_length=200,
73
        >>>                                null=True,
74
        >>>                                blank=True)
75
        >>>     company_phone_number = models.CharField(max_length=200,
76
        >>>                                             null=True,
77
        >>>                                             blank=True)
78
        >>>     company_email = models.EmailField(null=True, blank=True)
79
        >>>     company_website = models.URLField(null=True, blank=True)
80
        >>>
81
        >>>     # This does not cause a model change
82
        >>>     personal_contact_information = NestedProxyField(
83
        >>>         'email',
84
        >>>         'phone_number',
85
        >>>         'website',
86
        >>>     )
87
        >>>
88
        >>>     # This does not cause a model change
89
        >>>     business_contact_information = NestedProxyField(
90
        >>>         'company',
91
        >>>         'company_email',
92
        >>>         'company_phone_number',
93
        >>>         'company_website',
94
        >>>     )
95
        >>>
96
        >>>     # This does not cause a model change
97
        >>>     contact_information = NestedProxyField(
98
        >>>         'personal_contact_information',
99
        >>>         'business_contact_information',
100
        >>>     )
101

102
    You could even do this (although the way it's written above is at the
103
    moment the preferred/recommended way of dealing with unlimited nesting
104
    depth.
105

106
        >>>     # This does not cause a model change
107
        >>>     contact_information = NestedProxyField(
108
        >>>         {
109
        >>>             'personal_contact_information': (
110
        >>>                 'email',
111
        >>>                 'phone_number',
112
        >>>                 'website',
113
        >>>             )
114
        >>>         },
115
        >>>         {
116
        >>>             'business_contact_information': (
117
        >>>                 'company',
118
        >>>                 'company_email',
119
        >>>                 'company_phone_number',
120
        >>>                 'company_website',
121
        >>>             )
122
        >>>         },
123
        >>>     )
124
    """
125

126
    __as_object = options.get("as_object", False)
5✔
127

128
    @property
5✔
129
    def proxy_field(self):
4✔
130
        """Proxy field."""
131
        obj = options.get("obj") if "obj" in options else self
5✔
132
        __dict = {}
5✔
133
        for __field in fields:
5✔
134
            # If dictionary
135
            if isinstance(__field, dict):
5✔
136
                for __key, __values in __field.items():
5✔
137
                    setattr(
5✔
138
                        obj.__class__,
139
                        __key,
140
                        NestedProxyField(*__values, obj=obj),
141
                    )
142
                    __dict.update({__key: getattr(obj, __key)})
5✔
143
            # If string
144
            else:
145
                if hasattr(self, __field):
5✔
146
                    __dict.update({__field: getattr(obj, __field)})
5✔
147
        if __as_object is True:
5✔
148
            return DictProxy(__dict)
5✔
149
        return __dict
5✔
150

151
    return proxy_field
5✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc