Skip to content

Commit a8a02f5

Browse files
committed
black
1 parent 0d0ae49 commit a8a02f5

File tree

9 files changed

+74
-174
lines changed

9 files changed

+74
-174
lines changed

drf_sideloading/mixins.py

Lines changed: 26 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,7 @@ def __init__(self, **kwargs):
2828
def check_sideloading_serializer_class(self):
2929
assert (
3030
self.sideloading_serializer_class is not None
31-
), "'{}' should either include a `sideloading_serializer_class` attribute, ".format(
32-
self.__class__.__name__
33-
)
31+
), "'{}' should either include a `sideloading_serializer_class` attribute, ".format(self.__class__.__name__)
3432
assert issubclass(
3533
self.sideloading_serializer_class, SideLoadableSerializer
3634
), "'{}' `sideloading_serializer_class` must be a SideLoadableSerializer subclass".format(
@@ -48,36 +46,26 @@ def check_sideloading_serializer_class(self):
4846
self.sideloading_serializer_class.Meta, "primary", None
4947
), "Sideloadable serializer must have a Meta attribute called primary!"
5048
assert (
51-
self.sideloading_serializer_class.Meta.primary
52-
in self.sideloading_serializer_class._declared_fields
49+
self.sideloading_serializer_class.Meta.primary in self.sideloading_serializer_class._declared_fields
5350
), "Sideloadable serializer Meta.primary must point to a field in the serializer!"
54-
if (
55-
getattr(self.sideloading_serializer_class.Meta, "prefetches", None)
56-
is not None
57-
):
51+
if getattr(self.sideloading_serializer_class.Meta, "prefetches", None) is not None:
5852
assert isinstance(
5953
self.sideloading_serializer_class.Meta.prefetches, dict
6054
), "Sideloadable serializer Meta attribute 'prefetches' must be a dict."
6155

6256
# check serializer fields:
6357
for name, field in self.sideloading_serializer_class._declared_fields.items():
64-
assert getattr(
65-
field, "many", None
66-
), "SideLoadable field '{}' must be set as many=True".format(name)
58+
assert getattr(field, "many", None), "SideLoadable field '{}' must be set as many=True".format(name)
6759

6860
# check serializer fields:
6961
for name, field in self.sideloading_serializer_class._declared_fields.items():
70-
assert getattr(
71-
field, "many", None
72-
), "SideLoadable field '{}' must be set as many=True".format(name)
62+
assert getattr(field, "many", None), "SideLoadable field '{}' must be set as many=True".format(name)
7363

7464
def get_primary_field_name(self):
7565
return self.sideloading_serializer_class.Meta.primary
7666

7767
def get_sideloadable_fields(self):
78-
sideloadable_fields = copy.deepcopy(
79-
self.sideloading_serializer_class._declared_fields
80-
)
68+
sideloadable_fields = copy.deepcopy(self.sideloading_serializer_class._declared_fields)
8169
sideloadable_fields.pop(self._primary_field_name, None)
8270
return sideloadable_fields
8371

@@ -96,39 +84,28 @@ def get_sideloading_prefetches(self):
9684
return cleaned_prefetches
9785

9886
def initialize_request(self, request, *args, **kwargs):
99-
request = super(SideloadableRelationsMixin, self).initialize_request(
100-
request=request, *args, **kwargs
101-
)
87+
request = super(SideloadableRelationsMixin, self).initialize_request(request=request, *args, **kwargs)
10288

103-
sideload_params = self.parse_query_param(
104-
sideload_parameter=request.query_params.get(self.query_param_name, "")
105-
)
89+
sideload_params = self.parse_query_param(sideload_parameter=request.query_params.get(self.query_param_name, ""))
10690
if request.method == "GET" and sideload_params:
10791
# When sideloading disable BrowsableAPIForms
10892
if BrowsableAPIRenderer in self.renderer_classes:
10993
renderer_classes = (
110-
list(self.renderer_classes)
111-
if isinstance(self.renderer_classes, tuple)
112-
else self.renderer_classes
94+
list(self.renderer_classes) if isinstance(self.renderer_classes, tuple) else self.renderer_classes
11395
)
11496
renderer_classes = [
115-
BrowsableAPIRendererWithoutForms if r == BrowsableAPIRenderer else r
116-
for r in renderer_classes
97+
BrowsableAPIRendererWithoutForms if r == BrowsableAPIRenderer else r for r in renderer_classes
11798
]
11899
self.renderer_classes = renderer_classes
119100

120101
return request
121102

122103
def list(self, request, *args, **kwargs):
123-
sideload_params = self.parse_query_param(
124-
sideload_parameter=request.query_params.get(self.query_param_name, "")
125-
)
104+
sideload_params = self.parse_query_param(sideload_parameter=request.query_params.get(self.query_param_name, ""))
126105

127106
# Do not sideload unless params and GET method
128107
if request.method != "GET" or not sideload_params:
129-
return super(SideloadableRelationsMixin, self).list(
130-
request, *args, **kwargs
131-
)
108+
return super(SideloadableRelationsMixin, self).list(request, *args, **kwargs)
132109

133110
# After this `relations_to_sideload` is safe to use
134111
queryset = self.get_queryset()
@@ -145,17 +122,15 @@ def list(self, request, *args, **kwargs):
145122
sideloadable_page = self.get_sideloadable_page(page)
146123
serializer = self.sideloading_serializer_class(
147124
instance=sideloadable_page,
148-
fields_to_load=[self._primary_field_name]
149-
+ list(self.relations_to_sideload),
125+
fields_to_load=[self._primary_field_name] + list(self.relations_to_sideload),
150126
context={"request": request},
151127
)
152128
return self.get_paginated_response(serializer.data)
153129
else:
154130
sideloadable_page = self.get_sideloadable_page_from_queryset(queryset)
155131
serializer = self.sideloading_serializer_class(
156132
instance=sideloadable_page,
157-
fields_to_load=[self._primary_field_name]
158-
+ list(self.relations_to_sideload),
133+
fields_to_load=[self._primary_field_name] + list(self.relations_to_sideload),
159134
context={"request": request},
160135
)
161136
return Response(serializer.data)
@@ -171,67 +146,45 @@ def parse_query_param(self, sideload_parameter):
171146
This function finds string match between requested names and defined relation in view
172147
173148
"""
174-
self.relations_to_sideload = set(sideload_parameter.split(",")) & set(
175-
self._sideloadable_fields.keys()
176-
)
149+
self.relations_to_sideload = set(sideload_parameter.split(",")) & set(self._sideloadable_fields.keys())
177150
return self.relations_to_sideload
178151

179152
def get_relevant_prefetches(self):
180153
if not self._prefetches:
181154
return set()
182-
return set(
183-
pf
184-
for relation in self.relations_to_sideload
185-
for pf in self._prefetches.get(relation, [])
186-
)
155+
return set(pf for relation in self.relations_to_sideload for pf in self._prefetches.get(relation, []))
187156

188157
def get_sideloadable_page_from_queryset(self, queryset):
189158
# this works wonders, but can't be used when page is paginated...
190159
sideloadable_page = {self._primary_field_name: queryset}
191160
for relation in self.relations_to_sideload:
192161
if not isinstance(self._sideloadable_fields[relation], ListSerializer):
193-
raise RuntimeError(
194-
"SideLoadable field '{}' must be set as many=True".format(relation)
195-
)
162+
raise RuntimeError("SideLoadable field '{}' must be set as many=True".format(relation))
196163

197164
source = self._sideloadable_fields[relation].source or relation
198165
rel_model = self._sideloadable_fields[relation].child.Meta.model
199-
rel_qs = rel_model.objects.filter(
200-
pk__in=queryset.values_list(source, flat=True)
201-
)
166+
rel_qs = rel_model.objects.filter(pk__in=queryset.values_list(source, flat=True))
202167
sideloadable_page[source] = rel_qs
203168
return sideloadable_page
204169

205170
def get_sideloadable_page(self, page):
206171
sideloadable_page = {self._primary_field_name: page}
207172
for relation in self.relations_to_sideload:
208173
if not isinstance(self._sideloadable_fields[relation], ListSerializer):
209-
raise RuntimeError(
210-
"SideLoadable field '{}' must be set as many=True".format(relation)
211-
)
174+
raise RuntimeError("SideLoadable field '{}' must be set as many=True".format(relation))
212175

213176
source = self._sideloadable_fields[relation].source or relation
214-
sideloadable_page[source] = self.filter_related_objects(
215-
related_objects=page, lookup=source
216-
)
177+
sideloadable_page[source] = self.filter_related_objects(related_objects=page, lookup=source)
217178
return sideloadable_page
218179

219180
def filter_related_objects(self, related_objects, lookup):
220-
current_lookup, remaining_lookup = (
221-
lookup.split("__", 1) if "__" in lookup else (lookup, None)
222-
)
181+
current_lookup, remaining_lookup = lookup.split("__", 1) if "__" in lookup else (lookup, None)
223182
related_objects_set = {getattr(r, current_lookup) for r in related_objects} - {None}
224-
if related_objects_set and next(
225-
iter(related_objects_set)
226-
).__class__.__name__ in ["ManyRelatedManager", "RelatedManager"]:
227-
related_objects_set = set(
228-
chain(
229-
*[
230-
related_queryset.all()
231-
for related_queryset in related_objects_set
232-
]
233-
)
234-
)
183+
if related_objects_set and next(iter(related_objects_set)).__class__.__name__ in [
184+
"ManyRelatedManager",
185+
"RelatedManager",
186+
]:
187+
related_objects_set = set(chain(*[related_queryset.all() for related_queryset in related_objects_set]))
235188
if remaining_lookup:
236189
return self.filter_related_objects(related_objects_set, remaining_lookup)
237190
return set(related_objects_set) - {"", None}

drf_sideloading/serializers.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@
88
class SideLoadableSerializer(serializers.Serializer):
99
def __init__(self, instance=None, data=empty, fields_to_load=None, **kwargs):
1010
self.fields_to_load = fields_to_load
11-
super(SideLoadableSerializer, self).__init__(
12-
instance=instance, data=data, **kwargs
13-
)
11+
super(SideLoadableSerializer, self).__init__(instance=instance, data=data, **kwargs)
1412

1513
def to_representation(self, instance):
1614
"""
@@ -20,9 +18,7 @@ def to_representation(self, instance):
2018
fields = [
2119
f
2220
for f in self.fields.values()
23-
if not f.write_only
24-
and f.source in instance.keys()
25-
and f.field_name in self.fields_to_load
21+
if not f.write_only and f.source in instance.keys() and f.field_name in self.fields_to_load
2622
]
2723

2824
for field in fields:
@@ -36,9 +32,7 @@ def to_representation(self, instance):
3632
#
3733
# For related fields with `use_pk_only_optimization` we need to
3834
# resolve the pk value.
39-
check_for_none = (
40-
attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
41-
)
35+
check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
4236
if check_for_none is None:
4337
ret[field.field_name] = None
4438
else:

example/products/models.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@ class Partner(models.Model):
1515

1616
class Product(models.Model):
1717
name = models.CharField(max_length=255)
18-
category = models.ForeignKey(
19-
Category, on_delete=models.CASCADE, related_name="products"
20-
)
21-
supplier = models.ForeignKey(
22-
Supplier, on_delete=models.CASCADE, related_name="products"
23-
)
18+
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="products")
19+
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name="products")
2420
partners = models.ManyToManyField(Partner, related_name="products")

example/settings.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,7 @@
9090
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
9191

9292
AUTH_PASSWORD_VALIDATORS = [
93-
{
94-
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
95-
},
93+
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
9694
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
9795
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
9896
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},

pyproject.toml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
[tool.black]
2+
line-length = 120
3+
target-version = ["py37", "py38"]
4+
include = '\.pyi?$'
5+
exclude = '''
6+
/(
7+
\.git
8+
| build
9+
| dist
10+
11+
)/
12+
'''

tests/mixins.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
class OtherMixin(object):
2-
""" Mixin for testing purposes
3-
Check if `self.action` attribute is availavle
2+
"""Mixin for testing purposes
3+
Check if `self.action` attribute is availavle
44
"""
55

66
def get_serializer_class(self):

tests/models.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@ class Partner(models.Model):
1515

1616
class Product(models.Model):
1717
name = models.CharField(max_length=255)
18-
category = models.ForeignKey(
19-
Category, related_name="products", on_delete=models.CASCADE
20-
)
21-
supplier = models.ForeignKey(
22-
Supplier, related_name="products", on_delete=models.CASCADE
23-
)
18+
category = models.ForeignKey(Category, related_name="products", on_delete=models.CASCADE)
19+
supplier = models.ForeignKey(Supplier, related_name="products", on_delete=models.CASCADE)
2420
partners = models.ManyToManyField(Partner, related_name="products", blank=True)

tests/settings.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,4 @@
4242

4343
SITE_ID = 1
4444

45-
if django.VERSION >= (1, 10):
46-
MIDDLEWARE = ()
47-
else:
48-
MIDDLEWARE_CLASSES = ()
45+
MIDDLEWARE = ()

0 commit comments

Comments
 (0)