Skip to content

Commit c48f621

Browse files
author
Sourcery AI
committed
'Refactored by Sourcery'
1 parent c003165 commit c48f621

34 files changed

+217
-193
lines changed

django_sorcery/db/fields.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,8 @@ class Field(sa.Column):
4545
def __init__(self, *args, **kwargs):
4646
self.db = kwargs.pop("db", None)
4747

48-
name = None
4948
args = list(args)
50-
if args and isinstance(args[0], str):
51-
name = args.pop(0)
52-
49+
name = args.pop(0) if args and isinstance(args[0], str) else None
5350
column_type = kwargs.pop("type_", None)
5451
if args and hasattr(args[0], "_sqla_type"):
5552
column_type = args.pop(0)
@@ -266,11 +263,14 @@ def get_django_dialect_ranges(self):
266263
ops = operations.BaseDatabaseOperations
267264
with suppress(ImportError):
268265
ops = (
269-
import_string(DIALECT_MAP_TO_DJANGO.get(self.db.url.get_dialect().name) + ".base.DatabaseOperations")
266+
import_string(
267+
f"{DIALECT_MAP_TO_DJANGO.get(self.db.url.get_dialect().name)}.base.DatabaseOperations"
268+
)
270269
if self.db
271270
else operations.BaseDatabaseOperations
272271
)
273272

273+
274274
return ops.integer_field_ranges
275275

276276
def get_dialect_range(self):

django_sorcery/db/meta/column.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def clean(self, value, instance):
166166

167167
def validate(self, value, instance):
168168
"""Validate value and raise ValidationError if necessary."""
169-
getattr(instance, "clean_" + self.name, bool)()
169+
getattr(instance, f"clean_{self.name}", bool)()
170170

171171
def run_validators(self, value):
172172
"""Run field's validators and raise ValidationError if necessary."""
@@ -194,9 +194,7 @@ def __init__(self, column, prop=None, parent=None, name=None):
194194
self.field_kwargs["max_length"] = self.column.type.length
195195

196196
def to_python(self, value):
197-
if value is None:
198-
return value
199-
return str(value).strip()
197+
return value if value is None else str(value).strip()
200198

201199

202200
class text_column_info(string_column_info):
@@ -324,9 +322,7 @@ def to_python(self, value):
324322
return bool(value)
325323
if value in ("t", "T"):
326324
return True
327-
if value in ("f", "F"):
328-
return False
329-
return self.coercer.to_python(value)
325+
return False if value in ("f", "F") else self.coercer.to_python(value)
330326

331327

332328
class date_column_info(column_info):

django_sorcery/db/meta/model.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,8 @@ def __init__(self, model):
7676
app_config = apps.get_containing_app_config(self.model_class.__module__)
7777
self.app_label = getattr(app_config, "label", None) or "django_sorcery"
7878

79-
self.label = "{}.{}".format(self.app_label, self.object_name)
80-
self.label_lower = "{}.{}".format(self.app_label, self.model_name)
79+
self.label = f"{self.app_label}.{self.object_name}"
80+
self.label_lower = f"{self.app_label}.{self.model_name}"
8181

8282
sa.event.listen(self.mapper, "mapper_configured", self._init)
8383
self._init(self.mapper, self.model_class)
@@ -148,10 +148,16 @@ def __getattr__(self, name):
148148

149149
def __repr__(self):
150150
reprs = ["<model_info({!s})>".format(self.model_class.__name__)]
151-
reprs.extend(" " + repr(i) for i in self.primary_keys.values())
152-
reprs.extend(" " + repr(i) for _, i in sorted(self.properties.items()))
153-
reprs.extend(" " + i for i in chain(*[repr(c).split("\n") for _, c in sorted(self.composites.items())]))
154-
reprs.extend(" " + repr(i) for _, i in sorted(self.relationships.items()))
151+
reprs.extend(f" {repr(i)}" for i in self.primary_keys.values())
152+
reprs.extend(f" {repr(i)}" for _, i in sorted(self.properties.items()))
153+
reprs.extend(
154+
f" {i}"
155+
for i in chain(
156+
*[repr(c).split("\n") for _, c in sorted(self.composites.items())]
157+
)
158+
)
159+
160+
reprs.extend(f" {repr(i)}" for _, i in sorted(self.relationships.items()))
155161
return "\n".join(reprs)
156162

157163
@property
@@ -186,10 +192,7 @@ def primary_keys_from_dict(self, kwargs):
186192
if any(pk is None for pk in pks):
187193
return None
188194

189-
if len(pks) < 2:
190-
return next(iter(pks), None)
191-
192-
return tuple(pks)
195+
return next(iter(pks), None) if len(pks) < 2 else tuple(pks)
193196

194197
def primary_keys_from_instance(self, instance):
195198
"""Return a dict containing the primary keys of the ``instance``"""

django_sorcery/db/meta/relations.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ def __init__(self, relationship):
5555
self.local_remote_pairs_for_identity_key = []
5656
try:
5757
# ensure local_remote pairs are of same order as remote pk
58-
for i in target_pk:
59-
self.local_remote_pairs_for_identity_key.append((pairs[i], i))
58+
self.local_remote_pairs_for_identity_key.extend(
59+
(pairs[i], i) for i in target_pk
60+
)
61+
6062
except KeyError:
6163
# if relation is missing one of related pk columns
6264
# but actual constraint has it defined
@@ -78,8 +80,10 @@ def __init__(self, relationship):
7880

7981
if len(matching_constraints) == 1:
8082
pairs = {i.column: i.parent for i in matching_constraints[0].elements}
81-
for i in target_pk:
82-
self.local_remote_pairs_for_identity_key.append((pairs[i], i))
83+
self.local_remote_pairs_for_identity_key.extend(
84+
(pairs[i], i) for i in target_pk
85+
)
86+
8387
else:
8488
# if everything fails, return default pairs
8589
self.local_remote_pairs_for_identity_key = self.local_remote_pairs[:]
@@ -98,10 +102,7 @@ def get_form_class(self):
98102
from ...fields import ModelChoiceField
99103
from ...fields import ModelMultipleChoiceField
100104

101-
if self.uselist:
102-
return ModelMultipleChoiceField
103-
104-
return ModelChoiceField
105+
return ModelMultipleChoiceField if self.uselist else ModelChoiceField
105106

106107
def __repr__(self):
107-
return "<relation_info({}.{})>".format(self.parent_model.__name__, self.name)
108+
return f"<relation_info({self.parent_model.__name__}.{self.name})>"

django_sorcery/db/models.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,9 +233,9 @@ class BaseMeta(sqlalchemy.ext.declarative.DeclarativeMeta):
233233
"""Base metaclass for models which registers models to DB model registry
234234
when models are created."""
235235

236-
def __new__(mcs, name, bases, attrs):
237-
klass = super().__new__(mcs, name, bases, attrs)
238-
mcs.db.models_registry.append(klass)
236+
def __new__(cls, name, bases, attrs):
237+
klass = super().__new__(cls, name, bases, attrs)
238+
cls.db.models_registry.append(klass)
239239
return klass
240240

241241

django_sorcery/db/profiler.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,17 +190,20 @@ def process_response(self, request, response):
190190
try:
191191
stats = self.profiler.stats
192192
if stats["duration"] or self.log_results:
193-
self.log(**{"sa_{}".format(k): v for k, v in stats.items()})
193+
self.log(**{f"sa_{k}": v for k, v in stats.items()})
194194
except Exception: # pragma: nocover
195195
# The show must go on...
196196
pass # pragma: nocover
197197
else:
198198
if self.header_results:
199199
for k, v in stats.items():
200-
response["X-SA-{}".format("".join(i.title() for i in k.split("_")))] = v
200+
response[f'X-SA-{"".join(i.title() for i in k.split("_"))}'] = v
201201
self.profiler.clear()
202202
return response
203203

204204
def log(self, **kwargs):
205205
"""Log sqlalchemy stats for current request."""
206-
self.logger.info("SQLAlchemy profiler %s", " ".join("{}={}".format(k, v) for k, v in kwargs.items()))
206+
self.logger.info(
207+
"SQLAlchemy profiler %s",
208+
" ".join(f"{k}={v}" for k, v in kwargs.items()),
209+
)

django_sorcery/db/query.py

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""sqlalchemy query related things."""
2+
23
from collections import namedtuple
34
from functools import partial
45

@@ -14,34 +15,31 @@
1415
# todo add transforms support - e.g. column__date__gt
1516
LOOKUP_TO_EXPRESSION = {
1617
"contains": lambda column, value: column.contains(value),
17-
# "date"
18-
# "day"
1918
"endswith": lambda column, value: column.endswith(value),
2019
"exact": lambda column, value: column == value,
2120
"gt": lambda column, value: column > value,
2221
"gte": lambda column, value: column >= value,
23-
# "hour"
24-
"icontains": lambda column, value: sa.func.lower(column).contains(lower(value)),
25-
"iendswith": lambda column, value: sa.func.lower(column).endswith(lower(value)),
22+
"icontains": lambda column, value: sa.func.lower(column).contains(
23+
lower(value)
24+
),
25+
"iendswith": lambda column, value: sa.func.lower(column).endswith(
26+
lower(value)
27+
),
2628
"iexact": lambda column, value: sa.func.lower(column) == lower(value),
27-
"iin": lambda column, value: sa.func.lower(column).in_(lower(i) for i in value),
29+
"iin": lambda column, value: sa.func.lower(column).in_(
30+
lower(i) for i in value
31+
),
2832
"in": lambda column, value: column.in_(value),
29-
# "iregex"
30-
"isnull": lambda column, value: column == None if value else column != None, # noqa
31-
"istartswith": lambda column, value: sa.func.lower(column).startswith(lower(value)),
33+
"isnull": lambda column, value: column is None
34+
if value
35+
else column != None,
36+
"istartswith": lambda column, value: sa.func.lower(column).startswith(
37+
lower(value)
38+
),
3239
"lt": lambda column, value: column < value,
3340
"lte": lambda column, value: column <= value,
34-
# "minute"
35-
# "month"
36-
# "quarter"
3741
"range": lambda column, value: column.between(*value),
38-
# "regex"
39-
# "second"
4042
"startswith": lambda column, value: column.startswith(value),
41-
# "time"
42-
# "week"
43-
# "week_day"
44-
# "year"
4543
}
4644

4745

@@ -58,11 +56,7 @@ def get(self, *args, **kwargs):
5856
mapper = self._only_full_mapper_zero("get")
5957
pk = meta.model_info(mapper).primary_keys_from_dict(kwargs)
6058

61-
if pk is not None:
62-
return super().get(pk)
63-
64-
return None
65-
59+
return super().get(pk) if pk is not None else None
6660
return super().get(*args, **kwargs)
6761

6862
def order_by(self, *criterion):
@@ -236,11 +230,10 @@ def __get__(self, instance, owner):
236230

237231
if not model:
238232
raise AttributeError(
239-
"Cannot access {} when not bound to a model. "
240-
"You can explicitly instantiate descriptor with model class - `db.queryproperty(Model)`."
241-
"".format(self.__class__.__name__)
233+
f"Cannot access {self.__class__.__name__} when not bound to a model. You can explicitly instantiate descriptor with model class - `db.queryproperty(Model)`."
242234
)
243235

236+
244237
try:
245238
mapper = sa.orm.class_mapper(model)
246239
except sa.orm.exc.UnmappedClassError:

django_sorcery/db/sqlalchemy.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ def get(self):
3636

3737

3838
class _sqla_meta(type):
39-
def __new__(mcs, name, bases, attrs):
40-
typ = super().__new__(mcs, name, bases, attrs)
39+
def __new__(cls, name, bases, attrs):
40+
typ = super().__new__(cls, name, bases, attrs)
4141

4242
# figure out all props to be proxied
4343
dummy = sa.orm.Session()

django_sorcery/forms.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -191,11 +191,15 @@ class ModelFormMetaclass(DeclarativeFieldsMetaclass):
191191
def __new__(mcs, name, bases, attrs):
192192
cls = super().__new__(mcs, name, bases, attrs)
193193

194-
base_formfield_callback = None
195-
for base in bases:
196-
if hasattr(base, "Meta") and hasattr(base.Meta, "formfield_callback"):
197-
base_formfield_callback = base.Meta.formfield_callback
198-
break
194+
base_formfield_callback = next(
195+
(
196+
base.Meta.formfield_callback
197+
for base in bases
198+
if hasattr(base, "Meta")
199+
and hasattr(base.Meta, "formfield_callback")
200+
),
201+
None,
202+
)
199203

200204
formfield_callback = attrs.pop("formfield_callback", base_formfield_callback)
201205

@@ -331,9 +335,10 @@ def save(self, flush=True, **kwargs):
331335

332336
if self.errors:
333337
raise ValueError(
334-
"The {} could not be saved because the data didn't validate.".format(self.instance.__class__.__name__)
338+
f"The {self.instance.__class__.__name__} could not be saved because the data didn't validate."
335339
)
336340

341+
337342
if self.instance not in opts.session:
338343
opts.session.add(self.instance)
339344

@@ -372,7 +377,7 @@ def save_instance(self, instance=None, cleaned_data=None):
372377
def update_attribute(self, instance, name, field, value):
373378
"""Provides hooks for updating form instance's attribute for a field
374379
with value."""
375-
field_setter = getattr(self, "set_" + name, None)
380+
field_setter = getattr(self, f"set_{name}", None)
376381
if field_setter:
377382
field_setter(instance, name, field, value)
378383
else:
@@ -408,7 +413,7 @@ def modelform_factory(model, form=ModelForm, formfield_callback=None, **kwargs):
408413
if formfield_callback:
409414
meta_.formfield_callback = staticmethod(formfield_callback)
410415

411-
class_name = model.__name__ + "Form"
416+
class_name = f"{model.__name__}Form"
412417

413418
if getattr(meta_, "fields", None) is None and getattr(meta_, "exclude", None) is None:
414419
raise ImproperlyConfigured(

django_sorcery/formsets/base.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,11 @@ def __init__(self, data=None, files=None, auto_id="id_%s", prefix=None, queryset
3030

3131
def initial_form_count(self):
3232
"""Return the number of forms that are required in this FormSet."""
33-
if not (self.data or self.files):
34-
return len(self.get_queryset())
35-
36-
return super().initial_form_count()
33+
return (
34+
super().initial_form_count()
35+
if (self.data or self.files)
36+
else len(self.get_queryset())
37+
)
3738

3839
def _existing_object(self, pk):
3940
info = meta.model_info(self.model)
@@ -54,7 +55,7 @@ def _construct_form(self, i, **kwargs):
5455
info = meta.model_info(self.model)
5556
pks = {}
5657
for name, pk_info in info.primary_keys.items():
57-
pk_key = "{}-{}".format(self.add_prefix(i), name)
58+
pk_key = f"{self.add_prefix(i)}-{name}"
5859
pk_val = self.data.get(pk_key)
5960
pks[name] = pk_info.column.type.python_type(pk_val) if pk_val else None
6061

@@ -194,5 +195,5 @@ def modelformset_factory(
194195
validate_min=validate_min,
195196
validate_max=validate_max,
196197
)
197-
class_name = model.__name__ + "FormSet"
198+
class_name = f"{model.__name__}FormSet"
198199
return type(form)(str(class_name), (FormSet,), {"model": model, "session": session})

0 commit comments

Comments
 (0)