refactor: refactor unnecessary else / elif when if block has a return statement (#5735)

The use of `else` or `elif` becomes redundant and can be dropped if the last statement under the leading `if` / `elif` block is a `return` statement.
In the case of an `elif` after `return`, it can be written as a separate `if` block.
For `else` blocks after `return`, the statements can be shifted out of `else`. Please refer to the examples below for reference.

Refactoring the code this way can improve code-readability and make it easier to maintain.

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
This commit is contained in:
Matthias Mair 2023-10-18 00:06:54 +02:00 committed by GitHub
parent 3f93151cca
commit eb79bd1743
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 123 additions and 235 deletions

View File

@ -207,8 +207,6 @@ class APIDownloadMixin:
if export_format and export_format in ['csv', 'tsv', 'xls', 'xlsx']: if export_format and export_format in ['csv', 'tsv', 'xls', 'xlsx']:
queryset = self.filter_queryset(self.get_queryset()) queryset = self.filter_queryset(self.get_queryset())
return self.download_queryset(queryset, export_format) return self.download_queryset(queryset, export_format)
else:
# Default to the parent class implementation # Default to the parent class implementation
return super().get(request, *args, **kwargs) return super().get(request, *args, **kwargs)

View File

@ -20,7 +20,6 @@ def get_unit_registry():
# Cache the unit registry for speedier access # Cache the unit registry for speedier access
if _unit_registry is None: if _unit_registry is None:
return reload_unit_registry() return reload_unit_registry()
else:
return _unit_registry return _unit_registry
@ -145,7 +144,6 @@ def convert_physical_value(value: str, unit: str = None, strip_units=True):
return magnitude return magnitude
elif unit or value.units: elif unit or value.units:
return ureg.Quantity(magnitude, unit or value.units) return ureg.Quantity(magnitude, unit or value.units)
else:
return ureg.Quantity(magnitude) return ureg.Quantity(magnitude)

View File

@ -107,14 +107,12 @@ def getLogoImage(as_file=False, custom=True):
if storage is not None: if storage is not None:
if as_file: if as_file:
return f"file://{storage.path(settings.CUSTOM_LOGO)}" return f"file://{storage.path(settings.CUSTOM_LOGO)}"
else:
return storage.url(settings.CUSTOM_LOGO) return storage.url(settings.CUSTOM_LOGO)
# If we have got to this point, return the default logo # If we have got to this point, return the default logo
if as_file: if as_file:
path = settings.STATIC_ROOT.joinpath('img/inventree.png') path = settings.STATIC_ROOT.joinpath('img/inventree.png')
return f"file://{path}" return f"file://{path}"
else:
return getStaticUrl('img/inventree.png') return getStaticUrl('img/inventree.png')
@ -156,7 +154,6 @@ def str2bool(text, test=True):
""" """
if test: if test:
return str(text).lower() in ['1', 'y', 'yes', 't', 'true', 'ok', 'on', ] return str(text).lower() in ['1', 'y', 'yes', 't', 'true', 'ok', 'on', ]
else:
return str(text).lower() in ['0', 'n', 'no', 'none', 'f', 'false', 'off', ] return str(text).lower() in ['0', 'n', 'no', 'none', 'f', 'false', 'off', ]
@ -182,7 +179,6 @@ def is_bool(text):
return True return True
elif str2bool(text, False): elif str2bool(text, False):
return True return True
else:
return False return False

View File

@ -108,8 +108,6 @@ class AuthRequiredMiddleware(object):
# Save the 'next' parameter to pass through to the login view # Save the 'next' parameter to pass through to the login view
return redirect(f'{reverse_lazy("account_login")}?next={request.path}') return redirect(f'{reverse_lazy("account_login")}?next={request.path}')
else:
# Return a 401 (Unauthorized) response code for this request # Return a 401 (Unauthorized) response code for this request
return HttpResponse('Unauthorized', status=401) return HttpResponse('Unauthorized', status=401)

View File

@ -231,7 +231,6 @@ class ReferenceIndexingMixin(models.Model):
if query.exists(): if query.exists():
return query.first() return query.first()
else:
return None return None
@classmethod @classmethod
@ -471,7 +470,6 @@ class InvenTreeAttachment(models.Model):
"""Human name for attachment.""" """Human name for attachment."""
if self.attachment is not None: if self.attachment is not None:
return os.path.basename(self.attachment.name) return os.path.basename(self.attachment.name)
else:
return str(self.link) return str(self.link)
attachment = models.FileField(upload_to=rename_attachment, verbose_name=_('Attachment'), attachment = models.FileField(upload_to=rename_attachment, verbose_name=_('Attachment'),
@ -502,7 +500,6 @@ class InvenTreeAttachment(models.Model):
"""Base name/path for attachment.""" """Base name/path for attachment."""
if self.attachment: if self.attachment:
return os.path.basename(self.attachment.name) return os.path.basename(self.attachment.name)
else:
return None return None
@basename.setter @basename.setter

View File

@ -41,7 +41,6 @@ def inventreeInstanceTitle():
if common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE_TITLE", False): if common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE_TITLE", False):
return common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE", "") return common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE", "")
else:
return 'InvenTree' return 'InvenTree'
@ -73,7 +72,6 @@ def inventreeDocsVersion():
""" """
if isInvenTreeDevelopmentVersion(): if isInvenTreeDevelopmentVersion():
return "latest" return "latest"
else:
return INVENTREE_SW_VERSION # pragma: no cover return INVENTREE_SW_VERSION # pragma: no cover

View File

@ -43,7 +43,6 @@ def auth_request(request):
""" """
if request.user.is_authenticated: if request.user.is_authenticated:
return HttpResponse(status=200) return HttpResponse(status=200)
else:
return HttpResponse(status=403) return HttpResponse(status=403)
@ -222,7 +221,6 @@ class AjaxMixin(InvenTreeRoleMixin):
""" """
if method == 'POST': if method == 'POST':
return self.request.POST.get(name, None) return self.request.POST.get(name, None)
else:
return self.request.GET.get(name, None) return self.request.GET.get(name, None)
def get_data(self): def get_data(self):

View File

@ -46,7 +46,6 @@ class BuildFilter(rest_filters.FilterSet):
"""Filter the queryset to either include or exclude orders which are active.""" """Filter the queryset to either include or exclude orders which are active."""
if str2bool(value): if str2bool(value):
return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES) return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES)
else:
return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES) return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES)
overdue = rest_filters.BooleanFilter(label='Build is overdue', method='filter_overdue') overdue = rest_filters.BooleanFilter(label='Build is overdue', method='filter_overdue')
@ -55,7 +54,6 @@ class BuildFilter(rest_filters.FilterSet):
"""Filter the queryset to either include or exclude orders which are overdue.""" """Filter the queryset to either include or exclude orders which are overdue."""
if str2bool(value): if str2bool(value):
return queryset.filter(Build.OVERDUE_FILTER) return queryset.filter(Build.OVERDUE_FILTER)
else:
return queryset.exclude(Build.OVERDUE_FILTER) return queryset.exclude(Build.OVERDUE_FILTER)
assigned_to_me = rest_filters.BooleanFilter(label='assigned_to_me', method='filter_assigned_to_me') assigned_to_me = rest_filters.BooleanFilter(label='assigned_to_me', method='filter_assigned_to_me')
@ -69,7 +67,6 @@ class BuildFilter(rest_filters.FilterSet):
if value: if value:
return queryset.filter(responsible__in=owners) return queryset.filter(responsible__in=owners)
else:
return queryset.exclude(responsible__in=owners) return queryset.exclude(responsible__in=owners)
assigned_to = rest_filters.NumberFilter(label='responsible', method='filter_responsible') assigned_to = rest_filters.NumberFilter(label='responsible', method='filter_responsible')
@ -102,7 +99,6 @@ class BuildFilter(rest_filters.FilterSet):
"""Filter by whether or not the order has a project code""" """Filter by whether or not the order has a project code"""
if str2bool(value): if str2bool(value):
return queryset.exclude(project_code=None) return queryset.exclude(project_code=None)
else:
return queryset.filter(project_code=None) return queryset.filter(project_code=None)
@ -292,7 +288,6 @@ class BuildLineFilter(rest_filters.FilterSet):
"""Filter by whether each BuildLine is fully allocated""" """Filter by whether each BuildLine is fully allocated"""
if str2bool(value): if str2bool(value):
return queryset.filter(allocated__gte=F('quantity')) return queryset.filter(allocated__gte=F('quantity'))
else:
return queryset.filter(allocated__lt=F('quantity')) return queryset.filter(allocated__lt=F('quantity'))
available = rest_filters.BooleanFilter(label=_('Available'), method='filter_available') available = rest_filters.BooleanFilter(label=_('Available'), method='filter_available')
@ -310,7 +305,6 @@ class BuildLineFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.filter(flt) return queryset.filter(flt)
else:
return queryset.exclude(flt) return queryset.exclude(flt)
@ -508,7 +502,6 @@ class BuildItemFilter(rest_filters.FilterSet):
"""Filter the queryset based on whether build items are tracked""" """Filter the queryset based on whether build items are tracked"""
if str2bool(value): if str2bool(value):
return queryset.exclude(install_into=None) return queryset.exclude(install_into=None)
else:
return queryset.filter(install_into=None) return queryset.filter(install_into=None)

View File

@ -314,7 +314,6 @@ class Build(MPTTModel, InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models.
"""Return all Build Order objects under this one.""" """Return all Build Order objects under this one."""
if cascade: if cascade:
return Build.objects.filter(parent=self.pk) return Build.objects.filter(parent=self.pk)
else:
descendants = self.get_descendants(include_self=True) descendants = self.get_descendants(include_self=True)
Build.objects.filter(parent__pk__in=[d.pk for d in descendants]) Build.objects.filter(parent__pk__in=[d.pk for d in descendants])
@ -957,7 +956,6 @@ class Build(MPTTModel, InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models.
return 1 return 1
elif item.part in variant_parts: elif item.part in variant_parts:
return 2 return 2
else:
return 3 return 3
new_items = [] new_items = []

View File

@ -16,7 +16,6 @@ class SettingsAdmin(ImportExportModelAdmin):
"""Prevent the 'key' field being edited once the setting is created.""" """Prevent the 'key' field being edited once the setting is created."""
if obj: if obj:
return ['key'] return ['key']
else:
return [] return []
@ -29,7 +28,6 @@ class UserSettingsAdmin(ImportExportModelAdmin):
"""Prevent the 'key' field being edited once the setting is created.""" """Prevent the 'key' field being edited once the setting is created."""
if obj: if obj:
return ['key'] return ['key']
else:
return [] return []

View File

@ -206,7 +206,6 @@ class GlobalSettingsPermissions(permissions.BasePermission):
if request.method in ['GET', 'HEAD', 'OPTIONS']: if request.method in ['GET', 'HEAD', 'OPTIONS']:
return True return True
else:
# Any other methods require staff access permissions # Any other methods require staff access permissions
return user.is_staff return user.is_staff

View File

@ -404,7 +404,6 @@ class BaseInvenTreeSetting(models.Model):
if settings is not None and key in settings: if settings is not None and key in settings:
return settings[key] return settings[key]
else:
return {} return {}
@classmethod @classmethod
@ -458,7 +457,6 @@ class BaseInvenTreeSetting(models.Model):
if callable(default): if callable(default):
return default() return default()
else:
return default return default
@classmethod @classmethod
@ -881,8 +879,6 @@ class BaseInvenTreeSetting(models.Model):
elif self.is_model(): elif self.is_model():
return 'related field' return 'related field'
else:
return 'string' return 'string'
@classmethod @classmethod
@ -1891,7 +1887,6 @@ class InvenTreeSetting(BaseInvenTreeSetting):
if options: if options:
return options.get('requires_restart', False) return options.get('requires_restart', False)
else:
return False return False
@ -2430,7 +2425,6 @@ def get_price(instance, quantity, moq=True, multiples=True, currency=None, break
if pb_found: if pb_found:
cost = pb_cost * quantity cost = pb_cost * quantity
return InvenTree.helpers.normalize(cost + instance.base_cost) return InvenTree.helpers.normalize(cost + instance.base_cost)
else:
return None return None

View File

@ -480,7 +480,6 @@ class FileManagementAjaxView(AjaxView):
self.render_done(form) self.render_done(form)
data = {'form_valid': True, 'success': _('Parts imported')} data = {'form_valid': True, 'success': _('Parts imported')}
return self.renderJsonResponse(request, data=data) return self.renderJsonResponse(request, data=data)
else:
self.storage.current_step = self.steps.next self.storage.current_step = self.steps.next
return self.renderJsonResponse(request, data={'form_valid': None}) return self.renderJsonResponse(request, data={'form_valid': None})

View File

@ -195,14 +195,12 @@ class Company(InvenTreeNotesMixin, MetadataMixin, models.Model):
"""Return the URL of the image for this company.""" """Return the URL of the image for this company."""
if self.image: if self.image:
return InvenTree.helpers.getMediaUrl(self.image.url) return InvenTree.helpers.getMediaUrl(self.image.url)
else:
return InvenTree.helpers.getBlankImage() return InvenTree.helpers.getBlankImage()
def get_thumbnail_url(self): def get_thumbnail_url(self):
"""Return the URL for the thumbnail image for this Company.""" """Return the URL for the thumbnail image for this Company."""
if self.image: if self.image:
return InvenTree.helpers.getMediaUrl(self.image.thumbnail.url) return InvenTree.helpers.getMediaUrl(self.image.thumbnail.url)
else:
return InvenTree.helpers.getBlankThumbnail() return InvenTree.helpers.getBlankThumbnail()
@property @property
@ -849,7 +847,6 @@ class SupplierPart(MetadataMixin, InvenTreeBarcodeMixin, common.models.MetaMixin
if q is None or r is None: if q is None or r is None:
return 0 return 0
else:
return max(q - r, 0) return max(q - r, 0)
def purchase_orders(self): def purchase_orders(self):

View File

@ -171,7 +171,6 @@ class LabelPrintMixin(LabelFilterMixin):
if plugin.is_active(): if plugin.is_active():
# Only return the plugin if it is enabled! # Only return the plugin if it is enabled!
return plugin return plugin
else:
raise ValidationError(f"Plugin '{plugin_key}' is not enabled") raise ValidationError(f"Plugin '{plugin_key}' is not enabled")
else: else:
raise NotFound(f"Plugin '{plugin_key}' not found") raise NotFound(f"Plugin '{plugin_key}' not found")
@ -196,7 +195,6 @@ class LabelPrintMixin(LabelFilterMixin):
if isinstance(result, JsonResponse): if isinstance(result, JsonResponse):
result['plugin'] = plugin.plugin_slug() result['plugin'] = plugin.plugin_slug()
return result return result
else:
raise ValidationError(f"Plugin '{plugin.plugin_slug()}' returned invalid response type '{type(result)}'") raise ValidationError(f"Plugin '{plugin.plugin_slug()}' returned invalid response type '{type(result)}'")

View File

@ -20,7 +20,6 @@ class ProjectCodeResourceMixin:
"""Return the project code value, not the pk""" """Return the project code value, not the pk"""
if order.project_code: if order.project_code:
return order.project_code.code return order.project_code.code
else:
return '' return ''
@ -33,7 +32,6 @@ class TotalPriceResourceMixin:
"""Return the total price amount, not the object itself""" """Return the total price amount, not the object itself"""
if order.total_price: if order.total_price:
return order.total_price.amount return order.total_price.amount
else:
return '' return ''
@ -46,7 +44,6 @@ class PriceResourceMixin:
"""Return the price amount, not the object itself""" """Return the price amount, not the object itself"""
if line.price: if line.price:
return line.price.amount return line.price.amount
else:
return '' return ''
@ -175,7 +172,6 @@ class PurchaseOrderLineItemResource(PriceResourceMixin, InvenTreeResource):
"""Return a string value of the 'purchase_price' field, rather than the 'Money' object""" """Return a string value of the 'purchase_price' field, rather than the 'Money' object"""
if line.purchase_price: if line.purchase_price:
return line.purchase_price.amount return line.purchase_price.amount
else:
return '' return ''
@ -232,7 +228,6 @@ class SalesOrderLineItemResource(PriceResourceMixin, InvenTreeResource):
""" """
if item.sale_price: if item.sale_price:
return str(item.sale_price) return str(item.sale_price)
else:
return '' return ''

View File

@ -110,7 +110,6 @@ class OrderFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.filter(responsible__in=owners) return queryset.filter(responsible__in=owners)
else:
return queryset.exclude(responsible__in=owners) return queryset.exclude(responsible__in=owners)
overdue = rest_filters.BooleanFilter(label='overdue', method='filter_overdue') overdue = rest_filters.BooleanFilter(label='overdue', method='filter_overdue')
@ -122,7 +121,6 @@ class OrderFilter(rest_filters.FilterSet):
""" """
if str2bool(value): if str2bool(value):
return queryset.filter(self.Meta.model.overdue_filter()) return queryset.filter(self.Meta.model.overdue_filter())
else:
return queryset.exclude(self.Meta.model.overdue_filter()) return queryset.exclude(self.Meta.model.overdue_filter())
outstanding = rest_filters.BooleanFilter(label='outstanding', method='filter_outstanding') outstanding = rest_filters.BooleanFilter(label='outstanding', method='filter_outstanding')
@ -131,7 +129,6 @@ class OrderFilter(rest_filters.FilterSet):
"""Generic filter for determining if an order is 'outstanding'""" """Generic filter for determining if an order is 'outstanding'"""
if str2bool(value): if str2bool(value):
return queryset.filter(status__in=self.Meta.model.get_status_class().OPEN) return queryset.filter(status__in=self.Meta.model.get_status_class().OPEN)
else:
return queryset.exclude(status__in=self.Meta.model.get_status_class().OPEN) return queryset.exclude(status__in=self.Meta.model.get_status_class().OPEN)
project_code = rest_filters.ModelChoiceFilter( project_code = rest_filters.ModelChoiceFilter(
@ -145,7 +142,6 @@ class OrderFilter(rest_filters.FilterSet):
"""Filter by whether or not the order has a project code""" """Filter by whether or not the order has a project code"""
if str2bool(value): if str2bool(value):
return queryset.exclude(project_code=None) return queryset.exclude(project_code=None)
else:
return queryset.filter(project_code=None) return queryset.filter(project_code=None)
@ -163,7 +159,6 @@ class LineItemFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.exclude(**filters) return queryset.exclude(**filters)
else:
return queryset.filter(**filters) return queryset.filter(**filters)
@ -427,7 +422,6 @@ class PurchaseOrderLineItemFilter(LineItemFilter):
"""Filter by "pending" status (order status = pending)""" """Filter by "pending" status (order status = pending)"""
if str2bool(value): if str2bool(value):
return queryset.filter(order__status__in=PurchaseOrderStatusGroups.OPEN) return queryset.filter(order__status__in=PurchaseOrderStatusGroups.OPEN)
else:
return queryset.exclude(order__status__in=PurchaseOrderStatusGroups.OPEN) return queryset.exclude(order__status__in=PurchaseOrderStatusGroups.OPEN)
received = rest_filters.BooleanFilter(label='received', method='filter_received') received = rest_filters.BooleanFilter(label='received', method='filter_received')
@ -441,7 +435,6 @@ class PurchaseOrderLineItemFilter(LineItemFilter):
if str2bool(value): if str2bool(value):
return queryset.filter(q) return queryset.filter(q)
else:
# Only count "pending" orders # Only count "pending" orders
return queryset.exclude(q).filter(order__status__in=PurchaseOrderStatusGroups.OPEN) return queryset.exclude(q).filter(order__status__in=PurchaseOrderStatusGroups.OPEN)
@ -749,7 +742,6 @@ class SalesOrderLineItemFilter(LineItemFilter):
if str2bool(value): if str2bool(value):
return queryset.filter(q) return queryset.filter(q)
else:
return queryset.exclude(q) return queryset.exclude(q)
@ -1003,7 +995,6 @@ class SalesOrderShipmentFilter(rest_filters.FilterSet):
"""Filter SalesOrder list by 'shipped' status (boolean)""" """Filter SalesOrder list by 'shipped' status (boolean)"""
if str2bool(value): if str2bool(value):
return queryset.exclude(shipment_date=None) return queryset.exclude(shipment_date=None)
else:
return queryset.filter(shipment_date=None) return queryset.filter(shipment_date=None)
delivered = rest_filters.BooleanFilter(label='delivered', method='filter_delivered') delivered = rest_filters.BooleanFilter(label='delivered', method='filter_delivered')
@ -1012,7 +1003,6 @@ class SalesOrderShipmentFilter(rest_filters.FilterSet):
"""Filter SalesOrder list by 'delivered' status (boolean)""" """Filter SalesOrder list by 'delivered' status (boolean)"""
if str2bool(value): if str2bool(value):
return queryset.exclude(delivery_date=None) return queryset.exclude(delivery_date=None)
else:
return queryset.filter(delivery_date=None) return queryset.filter(delivery_date=None)
@ -1240,7 +1230,6 @@ class ReturnOrderLineItemFilter(LineItemFilter):
"""Filter by 'received' field""" """Filter by 'received' field"""
if str2bool(value): if str2bool(value):
return queryset.exclude(received_date=None) return queryset.exclude(received_date=None)
else:
return queryset.filter(received_date=None) return queryset.filter(received_date=None)

View File

@ -1184,7 +1184,6 @@ class PurchaseOrderLineItem(OrderLineItem):
""" """
if self.part is None: if self.part is None:
return None return None
else:
return self.part.part return self.part.part
part = models.ForeignKey( part = models.ForeignKey(

View File

@ -820,7 +820,6 @@ class PartFilter(rest_filters.FilterSet):
"""Filter by whether the Part has units or not""" """Filter by whether the Part has units or not"""
if str2bool(value): if str2bool(value):
return queryset.exclude(units='') return queryset.exclude(units='')
else:
return queryset.filter(units='') return queryset.filter(units='')
# Filter by parts which have (or not) an IPN value # Filter by parts which have (or not) an IPN value
@ -830,7 +829,6 @@ class PartFilter(rest_filters.FilterSet):
"""Filter by whether the Part has an IPN (internal part number) or not""" """Filter by whether the Part has an IPN (internal part number) or not"""
if str2bool(value): if str2bool(value):
return queryset.exclude(IPN='') return queryset.exclude(IPN='')
else:
return queryset.filter(IPN='') return queryset.filter(IPN='')
# Regex filter for name # Regex filter for name
@ -855,7 +853,6 @@ class PartFilter(rest_filters.FilterSet):
# Ignore any parts which do not have a specified 'minimum_stock' level # Ignore any parts which do not have a specified 'minimum_stock' level
# Filter items which have an 'in_stock' level lower than 'minimum_stock' # Filter items which have an 'in_stock' level lower than 'minimum_stock'
return queryset.exclude(minimum_stock=0).filter(Q(total_in_stock__lt=F('minimum_stock'))) return queryset.exclude(minimum_stock=0).filter(Q(total_in_stock__lt=F('minimum_stock')))
else:
# Filter items which have an 'in_stock' level higher than 'minimum_stock' # Filter items which have an 'in_stock' level higher than 'minimum_stock'
return queryset.filter(Q(total_in_stock__gte=F('minimum_stock'))) return queryset.filter(Q(total_in_stock__gte=F('minimum_stock')))
@ -866,7 +863,6 @@ class PartFilter(rest_filters.FilterSet):
"""Filter by whether the Part has any stock""" """Filter by whether the Part has any stock"""
if str2bool(value): if str2bool(value):
return queryset.filter(Q(in_stock__gt=0)) return queryset.filter(Q(in_stock__gt=0))
else:
return queryset.filter(Q(in_stock__lte=0)) return queryset.filter(Q(in_stock__lte=0))
# unallocated_stock filter # unallocated_stock filter
@ -876,7 +872,6 @@ class PartFilter(rest_filters.FilterSet):
"""Filter by whether the Part has unallocated stock""" """Filter by whether the Part has unallocated stock"""
if str2bool(value): if str2bool(value):
return queryset.filter(Q(unallocated_stock__gt=0)) return queryset.filter(Q(unallocated_stock__gt=0))
else:
return queryset.filter(Q(unallocated_stock__lte=0)) return queryset.filter(Q(unallocated_stock__lte=0))
convert_from = rest_filters.ModelChoiceFilter(label="Can convert from", queryset=Part.objects.all(), method='filter_convert_from') convert_from = rest_filters.ModelChoiceFilter(label="Can convert from", queryset=Part.objects.all(), method='filter_convert_from')
@ -926,7 +921,6 @@ class PartFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.exclude(q_a | q_b) return queryset.exclude(q_a | q_b)
else:
return queryset.filter(q_a | q_b) return queryset.filter(q_a | q_b)
stocktake = rest_filters.BooleanFilter(label="Has stocktake", method='filter_has_stocktake') stocktake = rest_filters.BooleanFilter(label="Has stocktake", method='filter_has_stocktake')
@ -935,7 +929,6 @@ class PartFilter(rest_filters.FilterSet):
"""Filter the queryset based on whether stocktake data is available""" """Filter the queryset based on whether stocktake data is available"""
if str2bool(value): if str2bool(value):
return queryset.exclude(last_stocktake=None) return queryset.exclude(last_stocktake=None)
else:
return queryset.filter(last_stocktake=None) return queryset.filter(last_stocktake=None)
stock_to_build = rest_filters.BooleanFilter(label='Required for Build Order', method='filter_stock_to_build') stock_to_build = rest_filters.BooleanFilter(label='Required for Build Order', method='filter_stock_to_build')
@ -945,7 +938,6 @@ class PartFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
# Return parts which are required for a build order, but have not yet been allocated # Return parts which are required for a build order, but have not yet been allocated
return queryset.filter(required_for_build_orders__gt=F('allocated_to_build_orders')) return queryset.filter(required_for_build_orders__gt=F('allocated_to_build_orders'))
else:
# Return parts which are not required for a build order, or have already been allocated # Return parts which are not required for a build order, or have already been allocated
return queryset.filter(required_for_build_orders__lte=F('allocated_to_build_orders')) return queryset.filter(required_for_build_orders__lte=F('allocated_to_build_orders'))
@ -955,7 +947,6 @@ class PartFilter(rest_filters.FilterSet):
"""Filter the queryset based on whether the part is fully depleted of stock""" """Filter the queryset based on whether the part is fully depleted of stock"""
if str2bool(value): if str2bool(value):
return queryset.filter(Q(in_stock=0) & ~Q(stock_item_count=0)) return queryset.filter(Q(in_stock=0) & ~Q(stock_item_count=0))
else:
return queryset.exclude(Q(in_stock=0) & ~Q(stock_item_count=0)) return queryset.exclude(Q(in_stock=0) & ~Q(stock_item_count=0))
is_template = rest_filters.BooleanFilter() is_template = rest_filters.BooleanFilter()
@ -1075,7 +1066,6 @@ class PartList(PartMixin, APIDownloadMixin, ListCreateAPI):
return self.get_paginated_response(data) return self.get_paginated_response(data)
elif request.is_ajax(): elif request.is_ajax():
return JsonResponse(data, safe=False) return JsonResponse(data, safe=False)
else:
return Response(data) return Response(data)
def filter_queryset(self, queryset): def filter_queryset(self, queryset):
@ -1280,7 +1270,6 @@ class PartDetail(PartMixin, RetrieveUpdateDestroyAPI):
if not part.active: if not part.active:
# Delete # Delete
return super(PartDetail, self).destroy(request, *args, **kwargs) return super(PartDetail, self).destroy(request, *args, **kwargs)
else:
# Return 405 error # Return 405 error
message = 'Part is active: cannot delete' message = 'Part is active: cannot delete'
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, data=message) return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, data=message)
@ -1360,7 +1349,6 @@ class PartParameterTemplateFilter(rest_filters.FilterSet):
"""Filter queryset to include only PartParameterTemplates with choices.""" """Filter queryset to include only PartParameterTemplates with choices."""
if str2bool(value): if str2bool(value):
return queryset.exclude(Q(choices=None) | Q(choices='')) return queryset.exclude(Q(choices=None) | Q(choices=''))
else:
return queryset.filter(Q(choices=None) | Q(choices='')) return queryset.filter(Q(choices=None) | Q(choices=''))
has_units = rest_filters.BooleanFilter( has_units = rest_filters.BooleanFilter(
@ -1372,7 +1360,6 @@ class PartParameterTemplateFilter(rest_filters.FilterSet):
"""Filter queryset to include only PartParameterTemplates with units.""" """Filter queryset to include only PartParameterTemplates with units."""
if str2bool(value): if str2bool(value):
return queryset.exclude(Q(units=None) | Q(units='')) return queryset.exclude(Q(units=None) | Q(units=''))
else:
return queryset.filter(Q(units=None) | Q(units='')) return queryset.filter(Q(units=None) | Q(units=''))
@ -1656,7 +1643,6 @@ class BomFilter(rest_filters.FilterSet):
"""Filter the queryset based on whether each line item has any available stock""" """Filter the queryset based on whether each line item has any available stock"""
if str2bool(value): if str2bool(value):
return queryset.filter(available_stock__gt=0) return queryset.filter(available_stock__gt=0)
else:
return queryset.filter(available_stock=0) return queryset.filter(available_stock=0)
on_order = rest_filters.BooleanFilter(label="On order", method="filter_on_order") on_order = rest_filters.BooleanFilter(label="On order", method="filter_on_order")
@ -1665,7 +1651,6 @@ class BomFilter(rest_filters.FilterSet):
"""Filter the queryset based on whether each line item has any stock on order""" """Filter the queryset based on whether each line item has any stock on order"""
if str2bool(value): if str2bool(value):
return queryset.filter(on_order__gt=0) return queryset.filter(on_order__gt=0)
else:
return queryset.filter(on_order=0) return queryset.filter(on_order=0)
has_pricing = rest_filters.BooleanFilter(label="Has Pricing", method="filter_has_pricing") has_pricing = rest_filters.BooleanFilter(label="Has Pricing", method="filter_has_pricing")
@ -1677,7 +1662,6 @@ class BomFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.exclude(q_a | q_b) return queryset.exclude(q_a | q_b)
else:
return queryset.filter(q_a | q_b) return queryset.filter(q_a | q_b)
@ -1751,7 +1735,6 @@ class BomList(BomMixin, ListCreateDestroyAPIView):
return self.get_paginated_response(data) return self.get_paginated_response(data)
elif request.is_ajax(): elif request.is_ajax():
return JsonResponse(data, safe=False) return JsonResponse(data, safe=False)
else:
return Response(data) return Response(data)
def filter_queryset(self, queryset): def filter_queryset(self, queryset):

View File

@ -765,14 +765,12 @@ class Part(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, MPTTModel)
"""Return the URL of the image for this part.""" """Return the URL of the image for this part."""
if self.image: if self.image:
return helpers.getMediaUrl(self.image.url) return helpers.getMediaUrl(self.image.url)
else:
return helpers.getBlankImage() return helpers.getBlankImage()
def get_thumbnail_url(self): def get_thumbnail_url(self):
"""Return the URL of the image thumbnail for this part.""" """Return the URL of the image thumbnail for this part."""
if self.image: if self.image:
return helpers.getMediaUrl(self.image.thumbnail.url) return helpers.getMediaUrl(self.image.thumbnail.url)
else:
return helpers.getBlankThumbnail() return helpers.getBlankThumbnail()
def validate_unique(self, exclude=None): def validate_unique(self, exclude=None):
@ -1906,8 +1904,6 @@ class Part(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, MPTTModel)
elif bom_price_range is None: elif bom_price_range is None:
return buy_price_range return buy_price_range
else:
return ( return (
min(buy_price_range[0], bom_price_range[0]), min(buy_price_range[0], bom_price_range[0]),
max(buy_price_range[1], bom_price_range[1]) max(buy_price_range[1], bom_price_range[1])
@ -3102,7 +3098,6 @@ class PartStocktakeReport(models.Model):
"""Return the URL for the associaed report file for download""" """Return the URL for the associaed report file for download"""
if self.report: if self.report:
return self.report.url return self.report.url
else:
return None return None
date = models.DateField( date = models.DateField(
@ -3644,7 +3639,6 @@ class PartCategoryParameterTemplate(MetadataMixin, models.Model):
"""String representation of a PartCategoryParameterTemplate (admin interface).""" """String representation of a PartCategoryParameterTemplate (admin interface)."""
if self.default_value: if self.default_value:
return f'{self.category.name} | {self.parameter_template.name} | {self.default_value}' return f'{self.category.name} | {self.parameter_template.name} | {self.default_value}'
else:
return f'{self.category.name} | {self.parameter_template.name}' return f'{self.category.name} | {self.parameter_template.name}'
category = models.ForeignKey(PartCategory, category = models.ForeignKey(PartCategory,

View File

@ -486,8 +486,6 @@ def primitive_to_javascript(primitive):
elif type(primitive) in [int, float]: elif type(primitive) in [int, float]:
return primitive return primitive
else:
# Wrap with quotes # Wrap with quotes
return format_html("'{}'", primitive) # noqa: P103 return format_html("'{}'", primitive) # noqa: P103
@ -497,7 +495,6 @@ def js_bool(val):
"""Return a javascript boolean value (true or false)""" """Return a javascript boolean value (true or false)"""
if val: if val:
return 'true' return 'true'
else:
return 'false' return 'false'

View File

@ -41,8 +41,6 @@ class InvenTreeCurrencyExchange(APICallMixin, CurrencyExchangeMixin, InvenTreePl
rates[base_currency] = 1.00 rates[base_currency] = 1.00
return rates return rates
else:
logger.warning("Failed to update exchange rates from %s: Server returned status %s", self.api_url, response.status_code) logger.warning("Failed to update exchange rates from %s: Server returned status %s", self.api_url, response.status_code)
return None return None

View File

@ -90,5 +90,4 @@ class InvenTreeLabelPlugin(LabelPrintingMixin, SettingsMixin, InvenTreePlugin):
if debug: if debug:
return self.render_to_html(label, request, **kwargs) return self.render_to_html(label, request, **kwargs)
else:
return self.render_to_pdf(label, request, **kwargs) return self.render_to_pdf(label, request, **kwargs)

View File

@ -114,7 +114,6 @@ class MetaBase:
if config: if config:
return config.active return config.active
else:
return False # pragma: no cover return False # pragma: no cover

View File

@ -403,7 +403,6 @@ class PluginsRegistry:
if install_plugins_file(): if install_plugins_file():
settings.PLUGIN_FILE_CHECKED = True settings.PLUGIN_FILE_CHECKED = True
return 'first_run' return 'first_run'
else:
return False return False
# endregion # endregion

View File

@ -64,7 +64,6 @@ def getkey(container: dict, key):
if key in container: if key in container:
return container[key] return container[key]
else:
return None return None
@ -93,7 +92,6 @@ def asset(filename):
if debug_mode: if debug_mode:
return os.path.join(settings.MEDIA_URL, 'report', 'assets', filename) return os.path.join(settings.MEDIA_URL, 'report', 'assets', filename)
else:
return f"file://{full_path}" return f"file://{full_path}"
@ -137,7 +135,6 @@ def uploaded_image(filename, replace_missing=True, replacement_file='blank_image
# In debug mode, return a web path # In debug mode, return a web path
if exists: if exists:
return os.path.join(settings.MEDIA_URL, filename) return os.path.join(settings.MEDIA_URL, filename)
else:
return os.path.join(settings.STATIC_URL, 'img', replacement_file) return os.path.join(settings.STATIC_URL, 'img', replacement_file)
else: else:
# Return file path # Return file path
@ -209,7 +206,6 @@ def part_parameter(part: Part, parameter_name: str):
""" """
if type(part) is Part: if type(part) is Part:
return part.get_parameter(parameter_name) return part.get_parameter(parameter_name)
else:
return None return None

View File

@ -236,7 +236,6 @@ class StockLocationFilter(rest_filters.FilterSet):
"""Filter by whether or not the location has a location type""" """Filter by whether or not the location has a location type"""
if str2bool(value): if str2bool(value):
return queryset.exclude(location_type=None) return queryset.exclude(location_type=None)
else:
return queryset.filter(location_type=None) return queryset.filter(location_type=None)
@ -483,7 +482,6 @@ class StockFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
# Filter StockItem with either build allocations or sales order allocations # Filter StockItem with either build allocations or sales order allocations
return queryset.filter(Q(sales_order_allocations__isnull=False) | Q(allocations__isnull=False)) return queryset.filter(Q(sales_order_allocations__isnull=False) | Q(allocations__isnull=False))
else:
# Filter StockItem without build allocations or sales order allocations # Filter StockItem without build allocations or sales order allocations
return queryset.filter(Q(sales_order_allocations__isnull=True) & Q(allocations__isnull=True)) return queryset.filter(Q(sales_order_allocations__isnull=True) & Q(allocations__isnull=True))
@ -496,7 +494,6 @@ class StockFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.filter(StockItem.EXPIRED_FILTER) return queryset.filter(StockItem.EXPIRED_FILTER)
else:
return queryset.exclude(StockItem.EXPIRED_FILTER) return queryset.exclude(StockItem.EXPIRED_FILTER)
external = rest_filters.BooleanFilter(label=_('External Location'), method='filter_external') external = rest_filters.BooleanFilter(label=_('External Location'), method='filter_external')
@ -505,7 +502,6 @@ class StockFilter(rest_filters.FilterSet):
"""Filter by whether or not the stock item is located in an external location""" """Filter by whether or not the stock item is located in an external location"""
if str2bool(value): if str2bool(value):
return queryset.filter(location__external=True) return queryset.filter(location__external=True)
else:
return queryset.exclude(location__external=True) return queryset.exclude(location__external=True)
in_stock = rest_filters.BooleanFilter(label='In Stock', method='filter_in_stock') in_stock = rest_filters.BooleanFilter(label='In Stock', method='filter_in_stock')
@ -514,7 +510,6 @@ class StockFilter(rest_filters.FilterSet):
"""Filter by if item is in stock.""" """Filter by if item is in stock."""
if str2bool(value): if str2bool(value):
return queryset.filter(StockItem.IN_STOCK_FILTER) return queryset.filter(StockItem.IN_STOCK_FILTER)
else:
return queryset.exclude(StockItem.IN_STOCK_FILTER) return queryset.exclude(StockItem.IN_STOCK_FILTER)
available = rest_filters.BooleanFilter(label='Available', method='filter_available') available = rest_filters.BooleanFilter(label='Available', method='filter_available')
@ -528,7 +523,6 @@ class StockFilter(rest_filters.FilterSet):
# The 'quantity' field is greater than the calculated 'allocated' field # The 'quantity' field is greater than the calculated 'allocated' field
# Note that the item must also be "in stock" # Note that the item must also be "in stock"
return queryset.filter(StockItem.IN_STOCK_FILTER).filter(Q(quantity__gt=F('allocated'))) return queryset.filter(StockItem.IN_STOCK_FILTER).filter(Q(quantity__gt=F('allocated')))
else:
# The 'quantity' field is less than (or equal to) the calculated 'allocated' field # The 'quantity' field is less than (or equal to) the calculated 'allocated' field
return queryset.filter(Q(quantity__lte=F('allocated'))) return queryset.filter(Q(quantity__lte=F('allocated')))
@ -552,7 +546,6 @@ class StockFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.exclude(q) return queryset.exclude(q)
else:
return queryset.filter(q) return queryset.filter(q)
has_batch = rest_filters.BooleanFilter(label='Has batch code', method='filter_has_batch') has_batch = rest_filters.BooleanFilter(label='Has batch code', method='filter_has_batch')
@ -563,7 +556,6 @@ class StockFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.exclude(q) return queryset.exclude(q)
else:
return queryset.filter(q) return queryset.filter(q)
tracked = rest_filters.BooleanFilter(label='Tracked', method='filter_tracked') tracked = rest_filters.BooleanFilter(label='Tracked', method='filter_tracked')
@ -580,7 +572,6 @@ class StockFilter(rest_filters.FilterSet):
if str2bool(value): if str2bool(value):
return queryset.exclude(q_batch & q_serial) return queryset.exclude(q_batch & q_serial)
else:
return queryset.filter(q_batch & q_serial) return queryset.filter(q_batch & q_serial)
installed = rest_filters.BooleanFilter(label='Installed in other stock item', method='filter_installed') installed = rest_filters.BooleanFilter(label='Installed in other stock item', method='filter_installed')
@ -589,7 +580,6 @@ class StockFilter(rest_filters.FilterSet):
"""Filter stock items by "belongs_to" field being empty.""" """Filter stock items by "belongs_to" field being empty."""
if str2bool(value): if str2bool(value):
return queryset.exclude(belongs_to=None) return queryset.exclude(belongs_to=None)
else:
return queryset.filter(belongs_to=None) return queryset.filter(belongs_to=None)
has_installed_items = rest_filters.BooleanFilter(label='Has installed items', method='filter_has_installed') has_installed_items = rest_filters.BooleanFilter(label='Has installed items', method='filter_has_installed')
@ -598,7 +588,6 @@ class StockFilter(rest_filters.FilterSet):
"""Filter stock items by "belongs_to" field being empty.""" """Filter stock items by "belongs_to" field being empty."""
if str2bool(value): if str2bool(value):
return queryset.filter(installed_items__gt=0) return queryset.filter(installed_items__gt=0)
else:
return queryset.filter(installed_items=0) return queryset.filter(installed_items=0)
sent_to_customer = rest_filters.BooleanFilter(label='Sent to customer', method='filter_sent_to_customer') sent_to_customer = rest_filters.BooleanFilter(label='Sent to customer', method='filter_sent_to_customer')
@ -607,7 +596,6 @@ class StockFilter(rest_filters.FilterSet):
"""Filter by sent to customer.""" """Filter by sent to customer."""
if str2bool(value): if str2bool(value):
return queryset.exclude(customer=None) return queryset.exclude(customer=None)
else:
return queryset.filter(customer=None) return queryset.filter(customer=None)
depleted = rest_filters.BooleanFilter(label='Depleted', method='filter_depleted') depleted = rest_filters.BooleanFilter(label='Depleted', method='filter_depleted')
@ -616,7 +604,6 @@ class StockFilter(rest_filters.FilterSet):
"""Filter by depleted items.""" """Filter by depleted items."""
if str2bool(value): if str2bool(value):
return queryset.filter(quantity__lte=0) return queryset.filter(quantity__lte=0)
else:
return queryset.exclude(quantity__lte=0) return queryset.exclude(quantity__lte=0)
has_purchase_price = rest_filters.BooleanFilter(label='Has purchase price', method='filter_has_purchase_price') has_purchase_price = rest_filters.BooleanFilter(label='Has purchase price', method='filter_has_purchase_price')
@ -625,7 +612,6 @@ class StockFilter(rest_filters.FilterSet):
"""Filter by having a purchase price.""" """Filter by having a purchase price."""
if str2bool(value): if str2bool(value):
return queryset.exclude(purchase_price=None) return queryset.exclude(purchase_price=None)
else:
return queryset.filter(purchase_price=None) return queryset.filter(purchase_price=None)
ancestor = rest_filters.ModelChoiceFilter( ancestor = rest_filters.ModelChoiceFilter(
@ -896,7 +882,6 @@ class StockList(APIDownloadMixin, ListCreateDestroyAPIView):
return self.get_paginated_response(data) return self.get_paginated_response(data)
elif request.is_ajax(): elif request.is_ajax():
return JsonResponse(data, safe=False) return JsonResponse(data, safe=False)
else:
return Response(data) return Response(data)
def get_queryset(self, *args, **kwargs): def get_queryset(self, *args, **kwargs):
@ -1359,7 +1344,6 @@ class StockTrackingList(ListAPI):
return self.get_paginated_response(data) return self.get_paginated_response(data)
if request.is_ajax(): if request.is_ajax():
return JsonResponse(data, safe=False) return JsonResponse(data, safe=False)
else:
return Response(data) return Response(data)
def create(self, request, *args, **kwargs): def create(self, request, *args, **kwargs):

View File

@ -1842,7 +1842,6 @@ class StockItem(InvenTreeBarcodeMixin, InvenTreeNotesMixin, MetadataMixin, commo
self.delete() self.delete()
return False return False
else:
self.save() self.save()
return True return True
@ -2234,7 +2233,6 @@ class StockItemTracking(models.Model):
"""Return label.""" """Return label."""
if self.tracking_type in StockHistoryCode.keys(): if self.tracking_type in StockHistoryCode.keys():
return StockHistoryCode.label(self.tracking_type) return StockHistoryCode.label(self.tracking_type)
else:
return self.title return self.title
tracking_type = models.IntegerField( tracking_type = models.IntegerField(

View File

@ -308,7 +308,6 @@ class RuleSet(models.Model):
return f'{str(self.group).ljust(15)}: {self.name.title().ljust(15)} | ' \ return f'{str(self.group).ljust(15)}: {self.name.title().ljust(15)} | ' \
f'v: {str(self.can_view).ljust(5)} | a: {str(self.can_add).ljust(5)} | ' \ f'v: {str(self.can_view).ljust(5)} | a: {str(self.can_add).ljust(5)} | ' \
f'c: {str(self.can_change).ljust(5)} | d: {str(self.can_delete).ljust(5)}' f'c: {str(self.can_change).ljust(5)} | d: {str(self.can_delete).ljust(5)}'
else:
return self.name return self.name
def save(self, *args, **kwargs): def save(self, *args, **kwargs):