refactor(backend): move mixins to generic (#13293)

* move mixins to generic

* fix imports

* fix import

* move InvenTreePermissionCheckMixin

* move base models

* move InvenTreeAuditMixin

* move PathStringMixin

* move ContentTypeMixin

* move MetadataMixin, PluginValidationMixin

* move ReferenceIndexingMixin

* fix import paths

* update doc paths

* fix imports

* internalize diff base

* add legacy imports

* rename metadata mixin

* rename PathStringMixin

* rename PluginValidationMixin

* rename ReferenceIndexingMixin

* add changelog entry

* document base clases

* add docs for model mixins

* add the rest of doc strings
This commit is contained in:
Matthias Mair authored and GitHub committed 2026-11-23 09:44:54 +11:00
1 parent 8ebb7a0e20
commit afc88f56e8
39 files changed
+2172 -2048

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Breaking Changes
- [#13271](https://github.com/inventree/InvenTree/pull/13271) makes a number of API fields read-only, as they are managed by dedicated endpoints and must not be edited directly: `consumed` (BuildLine), `received_date` (ReturnOrderLineItem), `barcode_hash` (ManufacturerPart, SalesOrderShipment), `issue_date` (SalesOrder, ReturnOrder, TransferOrder) and `complete_date` (ReturnOrder, TransferOrder). Values provided for these fields are now ignored.
- [#13293](https://github.com/inventree/InvenTree/pull/13293) moves various (internal) model base classes, if your plugin uses InvenTree base classes update your imports from InvenTree.models to generic.models before the next major release.
### Added
+1 -1
View File
@@ -86,7 +86,7 @@ To try it just copy the file to src/InvenTree/plugins and restart the server. Op
To implement a custom internal barcode format, the `generate(...)` method from the Barcode Mixin needs to be overridden. Then the plugin can be selected at `System Settings > Barcodes > Barcode Generation Plugin`.
```python
from InvenTree.models import InvenTreeBarcodeMixin
from generic.models.modelmixins import InvenTreeBarcodeMixin
from plugin import InvenTreePlugin
from plugin.mixins import BarcodeMixin
+66 -2
View File
@@ -23,14 +23,78 @@ This configuration ensures that Django recognizes the plugin as a valid applicat
## Base classes
A typical Django model class is based on `django.db.models.Model`, which provides the core functionality for defining database models in Django. Alternatively, `InvenTree.models.InvenTreeModel` comes with a few additional core integrations (content type association, [plugin validation](./mixins/validation.md)) or `InvenTree.models.InvenTreeMetadataModel` which also includes [model metadata](./metadata.md) support for the model instances.
A typical Django model class is based on `django.db.models.Model`, which provides the core functionality for defining database models in Django.
Alternatively, `generic.models.base`contains a few base classes that plugins can also use.
### InvenTreeModel
Add support for content type association and [plugin validation](./mixins/validation.md).
### InvenTreeMetadataModel
Adds everything in InvenTreeModel, and adds support for [model metadata](./metadata.md).
### InvenTreeTree
For Tree models using django-mptt for hierarchies, also include content type association.
## Generic Model Mixins
### MetadataMixin
Most common mechanisms contained in InvenTree's own models are exposed in the `generic.models` module as a set of mixins that often also have detection for frontend components to provide functions automatically.
### InvenTreeAttachmentMixin
Adds support for use of [generic attachments](../concepts/attachments.md) with a models instances.
### InvenTreeAuditMixin
Adds support for [audit tracking](../concepts/audit.md) of model instances, including API and user interface generation.
### InvenTreeBarcodeMixin
Adds fields and functions for linking a [barcode](../barcodes/index.md) against model instances including lookup, assignment, and validation of barcodes against the API.
### InvenTreeImageMixin
Adds a `image` field to the model and automatic thumbnail generation for the uploaded images. This image can also be referenced in [reports](../report/report.md).
You must define a constant `IMAGE_RENAME` on the model class pointing to the function in your model that handles renaming uploaded images.
### InvenTreeMetadataMixin
Adds support for [model metadata](./metadata.md) support, allowing additional information to be attached to model instances. This metadata can be accessed and manipulated through the InvenTree API or by other plugins.
### InvenTreeNoteMixin
Adds support for defining and managing [notes](../concepts/notes.md) against model instances.
### InvenTreeParameterMixin
Adds support for [parameters](../concepts/parameters.md), allowing your models to use the parameter mechanism including proper permission checks and integration with the InvenTree API.
### InvenTreePathStringMixin
Adds a number of fields to support having hierarchical path strings persisted on model instances automatically. Used by parts and stock item.
!!! warning "Warning"
Use only after understanding the added computational and database load overhead.
### InvenTreePluginValidationMixin
Adds functions that extend save and delete operations of the model to call [plugins for validation](./mixins/validation.md) before committing changes to the database.
### InvenTreeReferenceIndexingMixin
Adds support for generating, validating and parsing [instance references](../settings/reference.md). Also adds a `reference_int` field that stores a converted value for the reference for use in ordering and indexing operations.
An optional constant `REFERENCE_PATTERN_SETTING` on the model class can be pointed to a settings name that will be used to control the [reference pattern](../settings/reference.md).
### InvenTreeTagsMixin
Adds the required mechanism for defining [tags](../concepts/tags.md) for model instances.
+1 -1
View File
@@ -37,7 +37,7 @@ class InvenTreeSearchFilter(filters.SearchFilter):
- search_notes: If True, 'notes' is added to the search_fields if it isn't already present
- search_regex: If True, search is performed on 'regex' comparison
"""
from InvenTree.models import InvenTreeNoteMixin
from generic.models.modelmixins import InvenTreeNoteMixin
# Set (and read, in filter_queryset) on self rather than returned some other
# way, since get_search_fields() only returns the field list, not the
@@ -42,7 +42,7 @@ def audit_parent(model) -> tuple[str, str]:
- If the parent is a foreign key field, the name of the related model is returned
- If the parent reference is resolved by a custom method, the method docstring summary is returned as a note
"""
from InvenTree.models import InvenTreeAuditMixin
from generic.models.modelmixins import InvenTreeAuditMixin
if model.AUDIT_PARENT_FIELD:
field = model._meta.get_field(model.AUDIT_PARENT_FIELD)
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -771,7 +771,8 @@ def rebuild_model_tree(model: str, tree_id: int) -> None:
"""
from django.apps import apps
import InvenTree.models
from generic.models.base import InvenTreeTree
from generic.models.modelmixins import InvenTreePathStringMixin
try:
model_class = apps.get_model(model)
@@ -779,7 +780,7 @@ def rebuild_model_tree(model: str, tree_id: int) -> None:
logger.warning("rebuild_model_tree: Model '%s' does not exist", model)
return
if not issubclass(model_class, InvenTree.models.InvenTreeTree):
if not issubclass(model_class, InvenTreeTree):
logger.warning("rebuild_model_tree: Model '%s' is not a tree model", model)
return
@@ -787,7 +788,7 @@ def rebuild_model_tree(model: str, tree_id: int) -> None:
model_class.rebuild_trees([tree_id])
# Rebuild the 'pathstring' values for the entire tree (if applicable)
if issubclass(model_class, InvenTree.models.PathStringMixin):
if issubclass(model_class, InvenTreePathStringMixin):
model_class.rebuild_tree_pathstring_values([tree_id]) # ty: ignore[invalid-attribute-access]
+1 -1
View File
@@ -861,7 +861,7 @@ class TestHelpers(TestCase):
def test_model_mixin(self):
"""Test the getModelsWithMixin function."""
from InvenTree.models import InvenTreeBarcodeMixin
from generic.models.modelmixins import InvenTreeBarcodeMixin
models = InvenTree.helpers_model.getModelsWithMixin(InvenTreeBarcodeMixin)
+1 -1
View File
@@ -45,7 +45,7 @@ def audited_models() -> list:
Uses the app registry rather than ContentTypes, so that no database access is required.
"""
from InvenTree.models import InvenTreeAuditMixin
from generic.models.modelmixins import InvenTreeAuditMixin
return sorted(
(
+24 -13
View File
@@ -25,7 +25,6 @@ import generic.states
import InvenTree.fields
import InvenTree.helpers
import InvenTree.helpers_model
import InvenTree.models
import InvenTree.ready
import InvenTree.tasks
import part.models
@@ -49,6 +48,18 @@ from build.validators import (
from common.models import ProjectCode
from common.settings import get_global_setting
from generic.enums import StringEnum
from generic.models.base import InvenTreeMetadataModel, InvenTreeModel, InvenTreeTree
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeAuditMixin,
InvenTreeBarcodeMixin,
InvenTreeMetadataMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
InvenTreePluginValidationMixin,
InvenTreeReferenceIndexingMixin,
InvenTreeTagsMixin,
)
from generic.states import (
DEFERRABLE,
Deprecations,
@@ -92,19 +103,19 @@ class BuildReportContext(report.mixins.BaseReportContext, TypedDict):
class Build(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.PluginValidationMixin,
InvenTreeAuditMixin,
InvenTreePluginValidationMixin,
report.mixins.InvenTreeReportMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreeBarcodeMixin,
InvenTree.models.InvenTreeNoteMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTree.models.ReferenceIndexingMixin,
InvenTreeParameterMixin,
InvenTreeAttachmentMixin,
InvenTreeBarcodeMixin,
InvenTreeNoteMixin,
InvenTreeTagsMixin,
InvenTreeReferenceIndexingMixin,
StateTransitionMixin,
StatusCodeMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeTree,
InvenTreeMetadataMixin,
InvenTreeTree,
):
"""A Build object organizes the creation of new StockItem objects from other existing StockItem objects.
@@ -2190,7 +2201,7 @@ class BuildLineReportContext(report.mixins.BaseReportContext, TypedDict):
quantity: decimal.Decimal
class BuildLine(report.mixins.InvenTreeReportMixin, InvenTree.models.InvenTreeModel):
class BuildLine(report.mixins.InvenTreeReportMixin, InvenTreeModel):
"""A BuildLine object links a BOMItem to a Build.
When a new Build is created, the BuildLine objects are created automatically.
@@ -2310,7 +2321,7 @@ class BuildLine(report.mixins.InvenTreeReportMixin, InvenTree.models.InvenTreeMo
return self.consumed >= self.quantity
class BuildItem(InvenTree.models.InvenTreeMetadataModel):
class BuildItem(InvenTreeMetadataModel):
"""A BuildItem links multiple StockItem objects to a Build.
These are used to allocate part stock to a build. Once the Build is completed, the parts are removed from stock and the BuildItemAllocation objects are removed.
+4 -4
View File
@@ -47,12 +47,12 @@ import common.filters
import common.models
import common.serializers
import InvenTree.conversion
import InvenTree.models
import InvenTree.ready
from common.icons import get_icon_packs
from common.serializers import OAuth2ApplicationSerializer
from common.settings import get_global_setting
from data_exporter.mixins import DataExportViewMixin
from generic.models.base import InvenTreeTree
from generic.states.api import urlpattern as generic_states_api_urls
from InvenTree.api import (
BulkCreateMixin,
@@ -1226,7 +1226,7 @@ class ParameterTemplateFilter(FilterSet):
})
# If the provided model is a "tree" structure, then we should also include any child objects in the filter
if isinstance(instance, InvenTree.models.InvenTreeTree):
if isinstance(instance, InvenTreeTree):
id_values = list(
instance.get_descendants(include_self=True).values_list('pk', flat=True)
)
@@ -1315,7 +1315,7 @@ class ParameterTemplateFilter(FilterSet):
return queryset.none()
# Account for potential tree structure in the related model
if isinstance(related_instance, InvenTree.models.InvenTreeTree):
if isinstance(related_instance, InvenTreeTree):
related_instances = list(
related_instance.get_descendants(include_self=True).values_list(
'pk', flat=True
@@ -1517,7 +1517,7 @@ class InstanceInfoView(APIView):
)
def get(self, request, *args, **kwargs):
"""Return counts of attachments, notes and parameters for the given instance."""
from InvenTree.models import (
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
@@ -2,7 +2,6 @@
import InvenTree.config
import InvenTree.fields
import InvenTree.models
import common.models
import common.validators
import django.db.models.deletion
@@ -11,7 +10,7 @@ import uuid
from django.conf import settings
from django.db import migrations, models, transaction
from moneyed import CURRENCIES
import generic.models.modelmixins
def set_default_currency(apps, schema_editor):
"""Migrate the currency setting from config.yml to db."""
@@ -235,7 +234,7 @@ class Migration(migrations.Migration):
options={
'verbose_name': 'Attachment',
},
bases=(InvenTree.models.PluginValidationMixin, models.Model),
bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model),
),
migrations.AlterField(
model_name='customunit',
@@ -280,7 +279,7 @@ class Migration(migrations.Migration):
options={
'verbose_name': 'Barcode Scan',
},
bases=(InvenTree.models.PluginValidationMixin, models.Model),
bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model),
),
migrations.CreateModel(
name='SelectionList',
@@ -299,7 +298,7 @@ class Migration(migrations.Migration):
'verbose_name': 'Selection List',
'verbose_name_plural': 'Selection Lists',
},
bases=(InvenTree.models.PluginValidationMixin, models.Model),
bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model),
),
migrations.CreateModel(
name='SelectionListEntry',
@@ -372,7 +371,7 @@ class Migration(migrations.Migration):
'ordering': ['-updated'],
'unique_together': {('key', 'global_id')},
},
bases=(InvenTree.models.PluginValidationMixin, models.Model),
bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model),
),
migrations.CreateModel(
name='EmailMessage',
@@ -1,12 +1,12 @@
# Generated by Django 5.2.8 on 2025-12-03 12:39
import InvenTree.models
import generic.models.modelmixins
import InvenTree.validators
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import generic.models.internal
class Migration(migrations.Migration):
@@ -124,8 +124,8 @@ class Migration(migrations.Migration):
"db_table": "part_partparametertemplate",
},
bases=(
InvenTree.models.ContentTypeMixin,
InvenTree.models.PluginValidationMixin,
generic.models.internal.ContentTypeMixin,
generic.models.modelmixins.InvenTreePluginValidationMixin,
models.Model,
),
),
@@ -237,8 +237,8 @@ class Migration(migrations.Migration):
"unique_together": {("model_type", "model_id", "template")},
},
bases=(
InvenTree.models.ContentTypeMixin,
InvenTree.models.PluginValidationMixin,
generic.models.internal.ContentTypeMixin,
generic.models.modelmixins.InvenTreePluginValidationMixin,
models.Model,
),
),
@@ -1,10 +1,11 @@
# Generated by Django 5.2.14 on 2026-05-18 14:16
import common.validators
import InvenTree.models
import generic.models.modelmixins
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import generic.models.internal
class Migration(migrations.Migration):
@@ -118,8 +119,8 @@ class Migration(migrations.Migration):
"verbose_name_plural": "Notes",
},
bases=(
InvenTree.models.ContentTypeMixin,
InvenTree.models.PluginValidationMixin,
generic.models.internal.ContentTypeMixin,
generic.models.modelmixins.InvenTreePluginValidationMixin,
models.Model,
),
),
+18 -43
View File
@@ -59,7 +59,6 @@ import InvenTree.conversion
import InvenTree.exceptions
import InvenTree.fields
import InvenTree.helpers
import InvenTree.models
import InvenTree.ready
import InvenTree.tasks
import InvenTree.validators
@@ -67,6 +66,14 @@ import users.models
from common.setting.type import InvenTreeSettingsKeyType, SettingsKeyType
from common.settings import get_global_setting, global_setting_overrides
from generic.enums import StringEnum
from generic.models.base import InvenTreeMetadataModel, InvenTreeModel
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeAuditMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
InvenTreeTagsMixin,
)
from generic.states import ColorEnum
from generic.states.custom import state_color_mappings
from InvenTree.cache import get_session_cache, set_session_cache
@@ -151,9 +158,7 @@ class UpdatedUserMixin(models.Model):
)
class ProjectCode(
InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeMetadataModel
):
class ProjectCode(InvenTreeAuditMixin, InvenTreeMetadataModel):
"""A ProjectCode is a unique identifier for a project."""
IMPORT_ID_FIELDS = ['code']
@@ -1279,7 +1284,7 @@ class BaseInvenTreeSetting(UpdatedUserMixin, models.Model):
return self.__class__.is_required(self.key, **self.get_filters_for_instance())
class InvenTreeSetting(InvenTree.models.InvenTreeAuditMixin, BaseInvenTreeSetting):
class InvenTreeSetting(InvenTreeAuditMixin, BaseInvenTreeSetting):
"""An InvenTreeSetting object is a key:value pair used for storing single values (e.g. one-off settings values).
The class provides a way of retrieving the value for a particular key,
@@ -1871,7 +1876,7 @@ class NewsFeedEntry(models.Model):
)
class CustomUnit(InvenTree.models.InvenTreeAuditMixin, models.Model):
class CustomUnit(InvenTreeAuditMixin, models.Model):
"""Model for storing custom physical unit definitions.
Model Attributes:
@@ -2032,12 +2037,7 @@ def rename_attachment(instance, filename: str):
)
class Attachment(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTree.models.InvenTreeModel,
):
class Attachment(InvenTreeAuditMixin, InvenTreeTagsMixin, InvenTreeMetadataModel):
"""Class which represents an uploaded file attachment.
An attachment can be either an uploaded file, or an external URL.
@@ -2322,8 +2322,6 @@ class Attachment(
def check_permission(self, permission, user):
"""Check if the user has the required permission for this attachment."""
from InvenTree.models import InvenTreeAttachmentMixin
model_class = common.validators.attachment_model_class_from_label(
self.model_type
)
@@ -2544,7 +2542,7 @@ class InvenTreeCustomUserStateModel(models.Model):
return cls
class SelectionList(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel):
class SelectionList(InvenTreeMetadataModel):
"""Class which represents a list of selectable items for parameters.
A lists selection options can be either manually defined, or sourced from a plugin.
@@ -2743,11 +2741,7 @@ class SelectionListEntry(models.Model):
return self.label
class ParameterTemplate(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeModel,
):
class ParameterTemplate(InvenTreeAuditMixin, InvenTreeMetadataModel):
"""A ParameterTemplate provides a template for defining parameter values against various models.
This allow for assigning arbitrary data fields against existing models,
@@ -2977,12 +2971,7 @@ def post_save_parameter_template(sender, instance, created, **kwargs):
)
class Parameter(
InvenTree.models.InvenTreeAuditMixin,
UpdatedUserMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeModel,
):
class Parameter(InvenTreeAuditMixin, UpdatedUserMixin, InvenTreeMetadataModel):
"""Class which represents a parameter value assigned to a particular model instance.
Attributes:
@@ -3183,8 +3172,6 @@ class Parameter(
def check_permission(self, permission, user):
"""Check if the user has the required permission for this parameter."""
from InvenTree.models import InvenTreeParameterMixin
model_class = self.model_type.model_class()
if not issubclass(model_class, InvenTreeParameterMixin):
@@ -3198,8 +3185,6 @@ class Parameter(
The linked content_object can implement custom checks by overriding
the 'check_parameter_edit' method.
"""
from InvenTree.models import InvenTreeParameterMixin
# content_object is None (rather than raising) if the target row is
# missing - GenericForeignKey.__get__ catches ObjectDoesNotExist
# internally, it never propagates it.
@@ -3210,8 +3195,6 @@ class Parameter(
def check_delete(self):
"""Check if this parameter can be deleted."""
from InvenTree.models import InvenTreeParameterMixin
instance = self.content_object
if instance and isinstance(instance, InvenTreeParameterMixin):
@@ -3266,9 +3249,7 @@ class Parameter(
return self.template.description
class Note(
UpdatedUserMixin, InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
):
class Note(UpdatedUserMixin, InvenTreeMetadataModel):
"""Class which represents a note assigned to a particular model instance.
Attributes:
@@ -3475,8 +3456,6 @@ class Note(
def check_save(self):
"""Check if this note can be saved."""
from InvenTree.models import InvenTreeNoteMixin
if self.template or not self.model_type:
return
@@ -3490,8 +3469,6 @@ class Note(
def check_delete(self):
"""Check if this note can be deleted."""
from InvenTree.models import InvenTreeNoteMixin
if self.template or not self.model_type:
return
@@ -3507,8 +3484,6 @@ class Note(
def check_permission(self, permission, user):
"""Check if the user has the required permission for this note."""
from InvenTree.models import InvenTreeNoteMixin
if self.template:
return user.is_staff
@@ -3615,7 +3590,7 @@ def after_notesimage_deleted(sender, instance, **kwargs):
)
class BarcodeScanResult(InvenTree.models.InvenTreeModel):
class BarcodeScanResult(InvenTreeModel):
"""Model for storing barcode scans results."""
BARCODE_SCAN_MAX_LEN = 250
@@ -3948,7 +3923,7 @@ class EmailMessage(models.Model):
return super().delete(*args, **kwargs)
class EmailThread(InvenTree.models.InvenTreeMetadataModel):
class EmailThread(InvenTreeMetadataModel):
"""Model for storing email threads."""
class Meta:
+5 -3
View File
@@ -22,12 +22,16 @@ import common.models as common_models
import common.validators
import generic.states.custom
from generic.modelfeatures import get_model_features
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
)
from importer.registry import register_importer
from InvenTree.apps import DEFAULT_OIDC_APP_ID
from InvenTree.helpers import get_objectreference
from InvenTree.helpers_model import construct_absolute_url
from InvenTree.mixins import DataImportExportSerializerMixin
from InvenTree.models import InvenTreeNoteMixin, InvenTreeParameterMixin
from InvenTree.serializers import (
ContentTypeField,
FilterableSerializerMixin,
@@ -892,8 +896,6 @@ class AttachmentSerializer(
def save(self, **kwargs):
"""Override the save method to handle the model_type field."""
from InvenTree.models import InvenTreeAttachmentMixin
model_type = self.validated_data.get('model_type', None)
if model_type is None and self.instance:
+12 -12
View File
@@ -28,16 +28,16 @@ def model_options_for_mixin(mixin_class) -> list:
def note_model_types():
"""Return a list of valid note model choices."""
import InvenTree.models
from generic.models.modelmixins import InvenTreeNoteMixin
return models_with_mixin(InvenTree.models.InvenTreeNoteMixin)
return models_with_mixin(InvenTreeNoteMixin)
def note_model_options():
"""Return a list of options for models which support notes."""
import InvenTree.models
from generic.models.modelmixins import InvenTreeNoteMixin
return model_options_for_mixin(InvenTree.models.InvenTreeNoteMixin)
return model_options_for_mixin(InvenTreeNoteMixin)
def validate_note_model_type(value):
@@ -65,16 +65,16 @@ def validate_note_model_type(value):
def parameter_model_types():
"""Return a list of valid parameter model choices."""
import InvenTree.models
from generic.models.modelmixins import InvenTreeParameterMixin
return models_with_mixin(InvenTree.models.InvenTreeParameterMixin)
return models_with_mixin(InvenTreeParameterMixin)
def parameter_model_options():
"""Return a list of options for models which support parameters."""
import InvenTree.models
from generic.models.modelmixins import InvenTreeParameterMixin
return model_options_for_mixin(InvenTree.models.InvenTreeParameterMixin)
return model_options_for_mixin(InvenTreeParameterMixin)
def parameter_template_model_options():
@@ -84,16 +84,16 @@ def parameter_template_model_options():
def attachment_model_types():
"""Return a list of valid attachment model choices."""
import InvenTree.models
from generic.models.modelmixins import InvenTreeAttachmentMixin
return models_with_mixin(InvenTree.models.InvenTreeAttachmentMixin)
return models_with_mixin(InvenTreeAttachmentMixin)
def attachment_model_options():
"""Return a list of options for models which support attachments."""
import InvenTree.models
from generic.models.modelmixins import InvenTreeAttachmentMixin
return model_options_for_mixin(InvenTree.models.InvenTreeAttachmentMixin)
return model_options_for_mixin(InvenTreeAttachmentMixin)
def attachment_model_class_from_label(label: str):
@@ -1,9 +1,9 @@
# Generated by Django 5.2.7 on 2025-11-04 20:59
import InvenTree.models
import stdimage.models
from django.db import migrations
import generic.models.modelmixins
class Migration(migrations.Migration):
@@ -15,6 +15,6 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='company',
name='image',
field=stdimage.models.StdImageField(blank=True, force_min_size=False, null=True, upload_to=InvenTree.models.InvenTreeImageMixin.rename_image, variations={'preview': (256, 256), 'thumbnail': (128, 128)}, verbose_name='Image'),
field=stdimage.models.StdImageField(blank=True, force_min_size=False, null=True, upload_to=generic.models.modelmixins.InvenTreeImageMixin.rename_image, variations={'preview': (256, 256), 'thumbnail': (128, 128)}, verbose_name='Image'),
),
]
+34 -30
View File
@@ -22,13 +22,22 @@ import common.currency
import common.models
import InvenTree.conversion
import InvenTree.helpers
import InvenTree.models
import InvenTree.ready
import InvenTree.validators
import report.mixins
from audit.helpers import audited_update
from common.currency import currency_code_default
from common.settings import get_global_setting
from generic.models.base import InvenTreeMetadataModel, InvenTreeModel
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeAuditMixin,
InvenTreeBarcodeMixin,
InvenTreeImageMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
InvenTreeTagsMixin,
)
from InvenTree.fields import InvenTreeURLField, RoundingDecimalField
from order.status_codes import PurchaseOrderStatusGroups
@@ -87,14 +96,14 @@ def default_internal_company() -> Optional[int]:
class Company(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.InvenTreeNoteMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTreeAuditMixin,
InvenTreeAttachmentMixin,
InvenTreeParameterMixin,
InvenTreeNoteMixin,
InvenTreeTagsMixin,
report.mixins.InvenTreeReportMixin,
InvenTree.models.InvenTreeImageMixin,
InvenTree.models.InvenTreeMetadataModel,
InvenTreeImageMixin,
InvenTreeMetadataModel,
):
"""A Company object represents an external company.
@@ -339,9 +348,7 @@ class Company(
).distinct()
class Contact(
InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeMetadataModel
):
class Contact(InvenTreeAuditMixin, InvenTreeMetadataModel):
"""A Contact represents a person who works at a particular company. A Company may have zero or more associated Contact objects.
Attributes:
@@ -384,7 +391,7 @@ class Contact(
return self.name
class Address(InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeModel):
class Address(InvenTreeAuditMixin, InvenTreeModel):
"""An address represents a physical location where the company is located. It is possible for a company to have multiple locations.
Attributes:
@@ -561,13 +568,13 @@ class Address(InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeMo
class ManufacturerPart(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.InvenTreeBarcodeMixin,
InvenTree.models.InvenTreeNoteMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTree.models.InvenTreeMetadataModel,
InvenTreeAuditMixin,
InvenTreeAttachmentMixin,
InvenTreeParameterMixin,
InvenTreeBarcodeMixin,
InvenTreeNoteMixin,
InvenTreeTagsMixin,
InvenTreeMetadataModel,
):
"""Represents a unique part as provided by a Manufacturer Each ManufacturerPart is identified by a MPN (Manufacturer Part Number) Each ManufacturerPart is also linked to a Part object. A Part may be available from multiple manufacturers.
@@ -680,15 +687,14 @@ class ManufacturerPart(
class SupplierPart(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeBarcodeMixin,
InvenTree.models.InvenTreeNoteMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTreeAuditMixin,
InvenTreeAttachmentMixin,
InvenTreeParameterMixin,
InvenTreeBarcodeMixin,
InvenTreeNoteMixin,
InvenTreeTagsMixin,
common.models.MetaMixin,
InvenTree.models.InvenTreeModel,
InvenTreeMetadataModel,
):
"""Represents a unique part as provided by a Supplier Each SupplierPart is identified by a SKU (Supplier Part Number) Each SupplierPart is also linked to a Part or ManufacturerPart object. A Part may be available from multiple suppliers.
@@ -1093,9 +1099,7 @@ class SupplierPart(
return s
class SupplierPriceBreak(
InvenTree.models.InvenTreeAuditMixin, common.models.PriceBreak
):
class SupplierPriceBreak(InvenTreeAuditMixin, common.models.PriceBreak):
"""Represents a quantity price break for a SupplierPart.
- Suppliers can offer discounts at larger quantities
@@ -4,7 +4,7 @@ from django.urls import reverse
from taggit.models import Tag
import InvenTree.models
from generic.models.modelmixins import InvenTreeNoteMixin
from InvenTree.unit_test import InvenTreeAPITestCase
from part.models import Part
@@ -60,7 +60,7 @@ class ContentTypeFeatureAPITests(InvenTreeAPITestCase):
class CustomFeatureMixin(ModelFeatureMixin):
MODEL_FEATURE = 'custom'
class CustomModel(CustomFeatureMixin, InvenTree.models.InvenTreeNoteMixin):
class CustomModel(CustomFeatureMixin, InvenTreeNoteMixin):
class Meta:
abstract = True
@@ -0,0 +1,394 @@
"""Base classes for building models."""
from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.db.models import QuerySet
from django.db.transaction import TransactionManagementError
from django.utils.translation import gettext_lazy as _
import structlog
from mptt.exceptions import InvalidMove
from mptt.models import MPTTModel
import InvenTree.exceptions
import InvenTree.sentry
from generic.models.internal import ContentTypeMixin
from generic.models.modelmixins import (
InvenTreeMetadataMixin,
InvenTreePluginValidationMixin,
)
logger = structlog.get_logger('inventree')
class InvenTreeModel(ContentTypeMixin, InvenTreePluginValidationMixin, models.Model):
"""Base class for InvenTree models, which provides some common functionality.
Includes the following mixins by default:
- PluginValidationMixin: Provides a hook for plugins to validate model instances
"""
class Meta:
"""Metaclass options."""
abstract = True
class InvenTreeMetadataModel(InvenTreeMetadataMixin, InvenTreeModel):
"""Base class for an InvenTree model which includes a metadata field."""
class Meta:
"""Metaclass options."""
abstract = True
class InvenTreeTree(ContentTypeMixin, MPTTModel):
"""Provides an abstracted self-referencing tree model, based on the MPTTModel class.
Our implementation provides the following key improvements:
- Allow tracking of separate concepts of "nodes" and "items"
- Better handling of deletion of nodes and items
- Ensure tree is correctly rebuilt after deletion and other operations
- Improved protection against recursive tree structures
"""
# How each node reference its parent object
NODE_PARENT_KEY = 'parent'
# How items (not nodes) are hooked into the tree
# e.g. for StockLocation, this value is 'location'
ITEM_PARENT_KEY = None
class Meta:
"""Metaclass defines extra model properties."""
abstract = True
class MPTTMeta:
"""MPTT metaclass options."""
order_insertion_by = ['name']
@transaction.atomic
def delete(self, *args, **kwargs):
"""Handle the deletion of a tree node.
kwargs:
delete_children: If True, delete all child nodes (otherwise, point to the parent of this node)
delete_items: If True, delete all items associated with this node (otherwise, point to the parent of this node)
Order of operations:
1. Update nodes and items under the current node
2. Delete this node
3. Rebuild the model tree
"""
delete_children = kwargs.pop('delete_children', False)
delete_items = kwargs.pop('delete_items', False)
# Ensure that we have the latest version of the database object
try:
self.refresh_from_db()
except self.__class__.DoesNotExist:
# If the object no longer exists, raise a ValidationError
raise ValidationError(
'Object %s of type %s no longer exists', str(self), str(self.__class__)
)
tree_id = self.tree_id
parent = getattr(self, self.NODE_PARENT_KEY, None)
# When deleting a top level node with multiple children,
# we need to assign a new tree_id to each child node
# otherwise they will all have the same tree_id (which is not allowed)
lower_trees = []
if not parent: # No parent, which means this is a top-level node
for child in self.get_children():
# Store a flattened list of node IDs for each of the lower trees
nodes = list(
child
.get_descendants(include_self=True)
.values_list('pk', flat=True)
.distinct()
)
lower_trees.append(nodes)
# 1. Update nodes and items under the current node
self.handle_tree_delete(
delete_children=delete_children, delete_items=delete_items
)
# 2. Delete *this* node
super().delete(*args, **kwargs)
# A set of tree_id values which need to be rebuilt
trees = set()
if tree_id:
# If this node had a tree_id, we need to rebuild that tree
trees.add(tree_id)
# Did we delete a top-level node?
next_tree_id = self.getNextTreeID()
# If there is only one sub-tree, it can retain the same tree_id value
for tree in lower_trees[1:]:
# Bulk update the tree_id for all lower nodes
lower_nodes = self.__class__.objects.filter(pk__in=tree)
lower_nodes.update(tree_id=next_tree_id)
trees.add(next_tree_id)
next_tree_id += 1
# 3. Rebuild the model tree(s) as required
self.__class__.rebuild_trees(trees)
def handle_tree_delete(self, delete_children=False, delete_items=False):
"""Delete a single instance of the tree, based on provided kwargs.
Removing a tree "node" from the database must be considered carefully,
based on what the user intends for any items which exist *under* that node.
- "children" are any nodes (of the same type) which exist *under* this node (e.g. PartCategory)
- "items" are any items (of a different type) which exist *under* this node (e.g. Part)
Arguments:
delete_children: If True, delete all child items
delete_items: If True, delete all items associated with this node
There are multiple scenarios we can consider here:
A) delete_children = True and delete_items = True
B) delete_children = True and delete_items = False
C) delete_children = False and delete_items = True
D) delete_children = False and delete_items = False
Note: re-parenting uses audited_update(), so that the change is recorded
for audited models (it falls back to a plain update() otherwise).
"""
from audit.helpers import audited_update
child_nodes = self.get_descendants(include_self=False)
# Case A: Delete all child items, and all child nodes.
# - Delete all items at any lower level
# - Delete all descendant nodes
if delete_children and delete_items:
self.delete_items(cascade=True)
self.delete_nodes(child_nodes)
# Case B: Delete all child nodes, but move all child items up to the parent
# - Move all items at any lower level to the parent of this item
# - Delete all descendant nodes
elif delete_children and not delete_items:
if items := self.get_items(cascade=True):
parent = getattr(self, self.NODE_PARENT_KEY, None)
audited_update(items, **{self.ITEM_PARENT_KEY: parent})
self.delete_nodes(child_nodes)
# Case C: Delete all child items, but keep all child nodes
# - Remove all items directly associated with this node
# - Move any direct child nodes up one level
elif not delete_children and delete_items:
self.delete_items(cascade=False)
parent = getattr(self, self.NODE_PARENT_KEY, None)
audited_update(self.get_children(), **{self.NODE_PARENT_KEY: parent})
# Case D: Keep all child items, and keep all child nodes
# - Move all items directly associated with this node up one level
# - Move any direct child nodes up one level
elif not delete_children and not delete_items:
parent = getattr(self, self.NODE_PARENT_KEY, None)
if items := self.get_items(cascade=False):
audited_update(items, **{self.ITEM_PARENT_KEY: parent})
audited_update(self.get_children(), **{self.NODE_PARENT_KEY: parent})
def delete_nodes(self, nodes):
"""Delete a set of nodes from the tree.
1. First, set the "parent" value for selected nodes to None
2. Then, perform bulk deletion of selected nodes
Step 1. is required because we cannot guarantee the order-of-operations in the db backend
Arguments:
nodes: A queryset of nodes to delete
"""
nodes.update(**{self.NODE_PARENT_KEY: None})
nodes.delete()
def api_instance_filters(self):
"""Instance filters for InvenTreeTree models."""
return {self.NODE_PARENT_KEY: {'exclude_tree': self.pk}}
def save(self, *args, **kwargs):
"""Custom save method for InvenTreeTree abstract model."""
db_instance = None
parent = getattr(self, self.NODE_PARENT_KEY, None)
if not self.tree_id:
if parent:
# If we have a parent, use the parent's tree_id
self.tree_id = parent.tree_id
self.level = parent.level + 1
else:
# Otherwise, we need to generate a new tree_id
self.tree_id = self.getNextTreeID()
if self.pk:
try:
db_instance = self.get_db_instance()
except self.__class__.DoesNotExist:
# If the instance does not exist, we cannot get the db instance
db_instance = None
try:
super().save(*args, **kwargs)
except InvalidMove:
# Provide better error for parent selection
raise ValidationError({self.NODE_PARENT_KEY: _('Invalid choice')})
trees = set()
parent = getattr(self, self.NODE_PARENT_KEY, None)
if db_instance:
# If the tree_id or parent has changed, we need to rebuild the tree
if getattr(db_instance, self.NODE_PARENT_KEY) != parent:
trees.add(db_instance.tree_id)
if db_instance.tree_id != self.tree_id:
trees.add(self.tree_id)
trees.add(db_instance.tree_id)
elif parent:
# New instance, so we need to rebuild the tree (if it has a parent)
trees.add(self.tree_id)
# Flag to indicate that a tree rebuild task was triggered by this save
self._tree_rebuild_offloaded = False
if len(trees) > 0:
# Offload the tree rebuild(s) to the background worker.
# Note that repeated calls are de-duplicated (per tree),
# so a bulk operation results in a single rebuild per affected tree.
ran_sync = self.__class__.offload_tree_rebuild(trees)
self._tree_rebuild_offloaded = True
if ran_sync:
# The tree was rebuilt synchronously, so refresh the instance
try:
self.refresh_from_db()
except TransactionManagementError:
# If we are inside a transaction block, we cannot refresh from db
pass
except Exception as e:
# Any other error is unexpected
InvenTree.sentry.report_exception(e)
InvenTree.exceptions.log_error(f'{self.__class__.__name__}.save')
@classmethod
def offload_tree_rebuild(cls, tree_ids) -> bool:
"""Offload a rebuild of the specified trees to the background worker.
- The tree structure (and pathstring values, where applicable) are rebuilt for each tree
- If the background worker is not running, the rebuild is performed synchronously
- Identical pending tasks are skipped, so repeated calls (e.g. during a bulk
operation) result in (at most) a single queued rebuild per affected tree
Returns:
bool: True if any rebuild was performed synchronously (in the calling thread)
"""
from InvenTree.tasks import offload_task
ran_sync = False
for tree_id in tree_ids:
if tree_id:
result = offload_task(
'InvenTree.tasks.rebuild_model_tree', cls._meta.label_lower, tree_id
)
if result is True:
# offload_task returns True if the task ran synchronously
ran_sync = True
return ran_sync
@classmethod
def rebuild_trees(cls, tree_ids) -> None:
"""Rebuild the specified trees, with fallback to a full rebuild.
- Perform a partial rebuild for each provided tree_id
- If any partial rebuild fails, rebuild the entire tree (expensive!!!)
"""
result = True
for tree_id in tree_ids:
if tree_id and not cls.partial_rebuild(tree_id):
result = False
if not result:
# Rebuild the entire tree (expensive!!!)
cls.objects.rebuild()
@classmethod
def partial_rebuild(cls, tree_id: int) -> bool:
"""Perform a partial rebuild of the tree structure.
If a failure occurs, log the error and return False.
"""
try:
cls.objects.partial_rebuild(tree_id)
return True
except Exception as e:
# This is a critical error, explicitly report to sentry
InvenTree.sentry.report_exception(e)
InvenTree.exceptions.log_error(f'{cls.__name__}.partial_rebuild')
logger.exception(
'Failed to rebuild tree <%s> for %s: %s', tree_id, cls.__name__, e
)
return False
def delete_items(self, cascade: bool = False):
"""Delete any 'items' which exist under this node in the tree.
- Note that an 'item' is an instance of a different model class.
- Not all tree structures will have items associated with them.
"""
if items := self.get_items(cascade=cascade):
items.delete()
def get_items(self, cascade: bool = False):
"""Return a queryset of items which exist *under* this node in the tree.
- For a StockLocation instance, this would be a queryset of StockItem objects
- For a PartCategory instance, this would be a queryset of Part objects
The default implementation returns None, indicating that no items exist under this node.
"""
return None
def getUniqueParents(self) -> QuerySet:
"""Return a flat set of all parent items that exist above this node."""
return self.get_ancestors()
def getUniqueChildren(self, include_self=True) -> QuerySet:
"""Return a flat set of all child items that exist under this node."""
return self.get_descendants(include_self=include_self)
@property
def has_children(self) -> bool:
"""True if there are any children under this item."""
return self.getUniqueChildren(include_self=False).count() > 0
@classmethod
def getNextTreeID(cls) -> int:
"""Return the next available tree_id for this model class."""
instance = cls.objects.order_by('-tree_id').first()
if instance:
return instance.tree_id + 1
else:
return 1
@@ -0,0 +1,91 @@
"""Internal model mixins for building InvenTree models."""
class InvenTreePermissionCheckMixin:
"""Provides an abstracted class for managing permissions against related fields."""
@classmethod
def check_related_permission(cls, permission, user) -> bool:
"""Check if the user has permission to perform the specified action on the attachment.
The default implementation runs a permission check against *this* model class,
but this can be overridden in the implementing class if required.
Arguments:
permission: The permission to check (add / change / view / delete)
user: The user to check against
Returns:
bool: True if the user has permission, False otherwise
"""
perm = f'{cls._meta.app_label}.{permission}_{cls._meta.model_name}'
return user.has_perm(perm)
class ContentTypeMixin:
"""Mixin class which supports retrieval of the ContentType for a model instance."""
@classmethod
def get_content_type(cls):
"""Return the ContentType object associated with this model."""
from django.contrib.contenttypes.models import ContentType
return ContentType.objects.get_for_model(cls)
class DiffMixin:
"""Mixin which can be used to determine which fields have changed, compared to the instance saved to the database."""
def get_db_instance(self):
"""Return the instance of the object saved in the database.
Returns:
object: Instance of the object saved in the database
"""
if self.pk:
try:
return self.__class__.objects.get(pk=self.pk)
except self.__class__.DoesNotExist:
pass
return None
def get_field_deltas(self):
"""Return a dict of field deltas.
Compares the current instance with the instance saved in the database,
and returns a dict of fields which have changed.
Returns:
dict: Dict of field deltas
"""
db_instance = self.get_db_instance()
if db_instance is None:
return {}
deltas = {}
for field in self._meta.fields:
if field.name == 'id':
continue
if field.is_relation:
# Compare the raw FK id first (no query) - only dereference to the
# full related object (one query each side) if it actually differs.
# In the common case (unchanged FK) this avoids two full-object
# fetches per relational field for every single save() call.
if getattr(self, field.attname) == getattr(db_instance, field.attname):
continue
if getattr(self, field.name) != getattr(db_instance, field.name):
deltas[field.name] = {
'old': getattr(db_instance, field.name),
'new': getattr(self, field.name),
}
return deltas
def has_field_changed(self, field_name):
"""Determine if a particular field has changed."""
return field_name in self.get_field_deltas()
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,6 @@
# Generated by Django 5.2.11 on 2026-02-27 22:00
import InvenTree.fields
import InvenTree.models
import django.core.validators
import django.db.models.deletion
import generic.states.fields
@@ -12,7 +11,8 @@ import order.status_codes
import order.validators
from django.conf import settings
from django.db import migrations, models
import generic.models.modelmixins
import generic.models.internal
class Migration(migrations.Migration):
@@ -289,10 +289,10 @@ class Migration(migrations.Migration):
bases=(
generic.states.states.StatusCodeMixin,
generic.states.transition.StateTransitionMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreePermissionCheckMixin,
InvenTree.models.ContentTypeMixin,
InvenTree.models.PluginValidationMixin,
generic.models.modelmixins.InvenTreeAttachmentMixin,
generic.models.internal.InvenTreePermissionCheckMixin,
generic.models.internal.ContentTypeMixin,
generic.models.modelmixins.InvenTreePluginValidationMixin,
models.Model,
),
),
@@ -422,8 +422,8 @@ class Migration(migrations.Migration):
"verbose_name": "Transfer Order Line Item",
},
bases=(
InvenTree.models.ContentTypeMixin,
InvenTree.models.PluginValidationMixin,
generic.models.internal.ContentTypeMixin,
generic.models.modelmixins.InvenTreePluginValidationMixin,
models.Model,
),
),
+27 -20
View File
@@ -25,7 +25,6 @@ from mptt.models import TreeForeignKey
import common.models as common_models
import InvenTree.helpers
import InvenTree.models
import InvenTree.ready
import InvenTree.tasks
import InvenTree.validators
@@ -51,6 +50,16 @@ from company.models import (
SupplierPart,
default_internal_company,
)
from generic.models.base import InvenTreeMetadataModel
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeAuditMixin,
InvenTreeBarcodeMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
InvenTreeReferenceIndexingMixin,
InvenTreeTagsMixin,
)
from generic.states import (
RETURN_VALUE,
Deprecations,
@@ -96,7 +105,7 @@ from stock.status_codes import StockHistoryCode, StockStatus
logger = structlog.get_logger('inventree')
class AuditedOrderMixin(InvenTree.models.InvenTreeAuditMixin):
class AuditedOrderMixin(InvenTreeAuditMixin):
"""Audit log configuration for order models."""
AUDIT_EXCLUDE_FIELDS = (
@@ -108,7 +117,7 @@ class AuditedOrderMixin(InvenTree.models.InvenTreeAuditMixin):
)
class AuditedLineItemMixin(InvenTree.models.InvenTreeAuditMixin):
class AuditedLineItemMixin(InvenTreeAuditMixin):
"""Audit log configuration for order line item models.
Changes to line items are included in the history of the order.
@@ -357,15 +366,14 @@ class TransferOrderReportContext(BaseOrderReportContext, TypedDict):
class Order(
StatusCodeMixin,
StateTransitionMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreeBarcodeMixin,
InvenTree.models.InvenTreeNoteMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTreeParameterMixin,
InvenTreeAttachmentMixin,
InvenTreeBarcodeMixin,
InvenTreeNoteMixin,
InvenTreeTagsMixin,
report.mixins.InvenTreeReportMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.ReferenceIndexingMixin,
InvenTree.models.InvenTreeModel,
InvenTreeReferenceIndexingMixin,
InvenTreeMetadataModel,
):
"""Abstract model for an order.
@@ -2185,7 +2193,7 @@ def after_save_sales_order(sender, instance: SalesOrder, created: bool, **kwargs
SalesOrderShipment.objects.create(order=instance, reference='1')
class OrderLineItem(InvenTree.models.InvenTreeMetadataModel):
class OrderLineItem(InvenTreeMetadataModel):
"""Abstract model for an order line item.
Attributes:
@@ -2747,15 +2755,14 @@ class SalesOrderShipmentReportContext(report.mixins.BaseReportContext, TypedDict
class SalesOrderShipment(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreeBarcodeMixin,
InvenTree.models.InvenTreeNoteMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTreeAuditMixin,
InvenTreeParameterMixin,
InvenTreeAttachmentMixin,
InvenTreeBarcodeMixin,
InvenTreeNoteMixin,
InvenTreeTagsMixin,
report.mixins.InvenTreeReportMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeModel,
InvenTreeMetadataModel,
):
"""The SalesOrderShipment model represents a physical shipment made against a SalesOrder.
@@ -1,8 +1,8 @@
# Generated by Django 5.2.7 on 2025-11-04 20:59
import InvenTree.models
import stdimage.models
from django.db import migrations
import generic.models.modelmixins
class Migration(migrations.Migration):
@@ -15,6 +15,6 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='part',
name='image',
field=stdimage.models.StdImageField(blank=True, force_min_size=False, null=True, upload_to=InvenTree.models.InvenTreeImageMixin.rename_image, variations={'preview': (256, 256), 'thumbnail': (128, 128)}, verbose_name='Image'),
field=stdimage.models.StdImageField(blank=True, force_min_size=False, null=True, upload_to=generic.models.modelmixins.InvenTreeImageMixin.rename_image, variations={'preview': (256, 256), 'thumbnail': (128, 128)}, verbose_name='Image'),
),
]
+34 -28
View File
@@ -34,7 +34,6 @@ import company.models
import InvenTree.conversion
import InvenTree.fields
import InvenTree.helpers
import InvenTree.models
import InvenTree.ready
import InvenTree.tasks
import part.helpers as part_helpers
@@ -46,6 +45,19 @@ from build import models as BuildModels
from build.status_codes import BuildStatusGroups
from common.icons import validate_icon
from common.settings import get_global_setting
from generic.models.base import InvenTreeMetadataModel, InvenTreeTree
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeAuditMixin,
InvenTreeBarcodeMixin,
InvenTreeImageMixin,
InvenTreeMetadataMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
InvenTreePathStringMixin,
InvenTreePluginValidationMixin,
InvenTreeTagsMixin,
)
from InvenTree import helpers, validators
from InvenTree.exceptions import log_error
from InvenTree.fields import InvenTreeURLField
@@ -62,12 +74,12 @@ logger = structlog.get_logger('inventree')
class PartCategory(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.PluginValidationMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.PathStringMixin,
InvenTree.models.InvenTreeTree,
InvenTreeAuditMixin,
InvenTreePluginValidationMixin,
InvenTreeParameterMixin,
InvenTreeMetadataMixin,
InvenTreePathStringMixin,
InvenTreeTree,
):
"""PartCategory provides hierarchical organization of Part objects.
@@ -348,7 +360,7 @@ def rename_part_image(instance, filename):
return os.path.join(base, fname)
class PartCategoryParameterTemplate(InvenTree.models.InvenTreeMetadataModel):
class PartCategoryParameterTemplate(InvenTreeMetadataModel):
"""A PartCategoryParameterTemplate creates a unique relationship between a PartCategory and a ParameterTemplate.
Multiple ParameterTemplate instances can be associated to a PartCategory to drive a default list of parameter templates attached to a Part instance upon creation.
@@ -462,17 +474,17 @@ class PartReportContext(report.mixins.BaseReportContext, TypedDict):
@cleanup.ignore
class Part(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.PluginValidationMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreeBarcodeMixin,
InvenTree.models.InvenTreeNoteMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTreeAuditMixin,
InvenTreePluginValidationMixin,
InvenTreeParameterMixin,
InvenTreeAttachmentMixin,
InvenTreeBarcodeMixin,
InvenTreeNoteMixin,
InvenTreeTagsMixin,
report.mixins.InvenTreeReportMixin,
InvenTree.models.InvenTreeImageMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeTree,
InvenTreeImageMixin,
InvenTreeMetadataMixin,
InvenTreeTree,
):
"""The Part object represents an abstract part, the 'concept' of an actual entity.
@@ -2737,7 +2749,7 @@ class PartCategoryStar(models.Model):
)
class PartTestTemplate(InvenTree.models.InvenTreeMetadataModel):
class PartTestTemplate(InvenTreeMetadataModel):
"""A PartTestTemplate defines a 'template' for a test which is required to be run against a StockItem (an instance of the Part).
The test template applies "recursively" to part variants, allowing tests to be
@@ -2902,11 +2914,7 @@ class PartTestTemplate(InvenTree.models.InvenTreeMetadataModel):
return [x.strip() for x in self.choices.split(',') if x.strip()]
class BomItem(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeModel,
):
class BomItem(InvenTreeAuditMixin, InvenTreeMetadataModel):
"""A BomItem links a part to its component items.
A part can have a BOM (bill of materials) which defines
@@ -3595,9 +3603,7 @@ def update_pricing_after_delete(sender, instance, **kwargs):
pass
class BomItemSubstitute(
InvenTree.models.InvenTreeAuditMixin, InvenTree.models.InvenTreeMetadataModel
):
class BomItemSubstitute(InvenTreeAuditMixin, InvenTreeMetadataModel):
"""A BomItemSubstitute provides a specification for alternative parts, which can be used in a bill of materials.
Attributes:
@@ -3684,7 +3690,7 @@ class BomItemSubstitute(
)
class PartRelated(InvenTree.models.InvenTreeMetadataModel):
class PartRelated(InvenTreeMetadataModel):
"""Store and handle related parts (eg. mating connector, crimps, etc.)."""
class Meta:
@@ -5,7 +5,7 @@ from typing import cast
import structlog
import InvenTree.helpers_model
from InvenTree.models import InvenTreeBarcodeMixin
from generic.models.modelmixins import InvenTreeBarcodeMixin
logger = structlog.get_logger('inventree')
@@ -9,8 +9,8 @@ from django.utils.translation import gettext_lazy as _
import structlog
from company.models import Company, ManufacturerPart, SupplierPart
from generic.models.modelmixins import InvenTreeBarcodeMixin
from InvenTree.exceptions import log_error
from InvenTree.models import InvenTreeBarcodeMixin
from order.models import PurchaseOrder
from part.models import Part
from plugin import PluginMixinEnum
@@ -13,8 +13,8 @@ from typing import cast
from django.utils.translation import gettext_lazy as _
from generic.models.modelmixins import InvenTreeBarcodeMixin
from InvenTree.helpers import hash_barcode
from InvenTree.models import InvenTreeBarcodeMixin
from plugin import InvenTreePlugin
from plugin.mixins import (
BarcodeMixin,
@@ -43,7 +43,7 @@ class ParameterExporter(DataExportMixin, InvenTreePlugin):
**kwargs,
) -> bool:
"""Supported if the base model implements the InvenTreeParameterMixin."""
from InvenTree.models import InvenTreeParameterMixin
from generic.models.modelmixins import InvenTreeParameterMixin
return issubclass(model_class, InvenTreeParameterMixin)
@@ -57,7 +57,7 @@ class ParameterExporter(DataExportMixin, InvenTreePlugin):
def prefetch_queryset(self, queryset):
"""Ensure that the associated parameters are prefetched."""
from InvenTree.models import InvenTreeParameterMixin
from generic.models.modelmixins import InvenTreeParameterMixin
queryset = InvenTreeParameterMixin.annotate_parameters(queryset)
return queryset
+2 -2
View File
@@ -12,13 +12,13 @@ from django.urls import reverse
from django.utils.translation import gettext_lazy as _
import common.models
import InvenTree.models
import plugin.staticfiles
from generic.models.modelmixins import InvenTreeMetadataMixin
from plugin import InvenTreePlugin, registry
from plugin.events import PluginEvents, trigger_event
class PluginConfig(InvenTree.models.MetadataMixin, models.Model):
class PluginConfig(InvenTreeMetadataMixin, models.Model):
"""A PluginConfig object holds settings for plugins.
Attributes:
+4 -8
View File
@@ -19,11 +19,11 @@ import common.currency
import common.models
import InvenTree.fields
import InvenTree.helpers
import InvenTree.models
import InvenTree.ready
import InvenTree.tasks
from common.currency import currency_code_default
from common.settings import get_global_setting
from generic.models.modelmixins import InvenTreeAuditMixin
from InvenTree import validators
from InvenTree.cache import get_session_cache, set_session_cache
from InvenTree.exceptions import log_error
@@ -34,7 +34,7 @@ from part.models import Part
logger = structlog.get_logger('inventree')
class PartPricing(InvenTree.models.InvenTreeAuditMixin, common.models.MetaMixin):
class PartPricing(InvenTreeAuditMixin, common.models.MetaMixin):
"""Model for caching min/max pricing information for a particular Part.
It is prohibitively expensive to calculate min/max pricing for a part "on the fly".
@@ -851,9 +851,7 @@ class PartPricing(InvenTree.models.InvenTreeAuditMixin, common.models.MetaMixin)
)
class PartSellPriceBreak(
InvenTree.models.InvenTreeAuditMixin, common.models.PriceBreak
):
class PartSellPriceBreak(InvenTreeAuditMixin, common.models.PriceBreak):
"""Represents a price break for selling this part."""
# Changes to a price break are included in the history of the part
@@ -881,9 +879,7 @@ class PartSellPriceBreak(
)
class PartInternalPriceBreak(
InvenTree.models.InvenTreeAuditMixin, common.models.PriceBreak
):
class PartInternalPriceBreak(InvenTreeAuditMixin, common.models.PriceBreak):
"""Represents a price break for internally selling this part."""
# Changes to a price break are included in the history of the part
@@ -1,10 +1,9 @@
# Generated by Django 4.2.11 on 2024-04-21 03:11
import InvenTree.models
import generic.models.modelmixins
import django.core.validators
from django.db import migrations, models
import report.helpers
import report.models
import report.validators
@@ -35,6 +34,6 @@ class Migration(migrations.Migration):
'abstract': False,
'unique_together': [('name', 'model_type')]
},
bases=(InvenTree.models.PluginValidationMixin, models.Model),
bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model),
),
]
@@ -1,9 +1,8 @@
# Generated by Django 4.2.11 on 2024-04-22 12:48
import InvenTree.models
import generic.models.modelmixins
import django.core.validators
from django.db import migrations, models
import report.models
import report.validators
@@ -34,6 +33,6 @@ class Migration(migrations.Migration):
'abstract': False,
'unique_together': {('name', 'model_type')},
},
bases=(InvenTree.models.PluginValidationMixin, models.Model),
bases=(generic.models.modelmixins.InvenTreePluginValidationMixin, models.Model),
),
]
+2 -5
View File
@@ -24,15 +24,14 @@ from pypdf import PdfWriter
import InvenTree.exceptions
import InvenTree.helpers
import InvenTree.models
import InvenTree.ready
import report.helpers
import report.validators
from common.models import DataOutput, RenderChoices, UpdatedUserMixin
from common.settings import get_global_setting
from company.models import Company
from generic.models.base import InvenTreeMetadataModel
from InvenTree.helpers_model import get_base_url
from InvenTree.models import MetadataMixin
from plugin import InvenTreePlugin, PluginMixinEnum, registry
from report.security import restricted_db_access
@@ -203,9 +202,7 @@ class ReportContextExtension(TypedDict):
merge: bool
class ReportTemplateBase(
MetadataMixin, UpdatedUserMixin, InvenTree.models.InvenTreeModel
):
class ReportTemplateBase(UpdatedUserMixin, InvenTreeMetadataModel):
"""Base class for reports, labels."""
class ModelChoices(RenderChoices):
@@ -1,6 +1,5 @@
# Generated by Django 3.0.5 on 2020-05-06 23:36
import InvenTree.models
from django.db import migrations, models
import django.db.models.deletion
+27 -21
View File
@@ -31,7 +31,6 @@ import build.models
import common.models
import InvenTree.exceptions
import InvenTree.helpers
import InvenTree.models
import InvenTree.ready
import InvenTree.tasks
import order.models
@@ -41,6 +40,18 @@ from common.icons import validate_icon
from common.settings import get_global_setting
from company import models as CompanyModels
from generic.enums import StringEnum
from generic.models.base import InvenTreeMetadataModel, InvenTreeTree
from generic.models.modelmixins import (
InvenTreeAttachmentMixin,
InvenTreeAuditMixin,
InvenTreeBarcodeMixin,
InvenTreeMetadataMixin,
InvenTreeNoteMixin,
InvenTreeParameterMixin,
InvenTreePathStringMixin,
InvenTreePluginValidationMixin,
InvenTreeTagsMixin,
)
from generic.states import StatusCodeMixin
from generic.states.fields import InvenTreeCustomStatusModelField
from InvenTree.fields import InvenTreeModelMoneyField, InvenTreeURLField
@@ -56,11 +67,7 @@ from users.models import Owner
logger = structlog.get_logger('inventree')
class StockLocationType(
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.MetadataMixin,
models.Model,
):
class StockLocationType(InvenTreeParameterMixin, InvenTreeMetadataMixin, models.Model):
"""A type of stock location like Warehouse, room, shelf, drawer.
Attributes:
@@ -130,14 +137,14 @@ class StockLocationReportContext(report.mixins.BaseReportContext):
class StockLocation(
InvenTree.models.PluginValidationMixin,
InvenTree.models.InvenTreeParameterMixin,
InvenTree.models.InvenTreeBarcodeMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTreePluginValidationMixin,
InvenTreeParameterMixin,
InvenTreeBarcodeMixin,
InvenTreeTagsMixin,
report.mixins.InvenTreeReportMixin,
InvenTree.models.PathStringMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeTree,
InvenTreePathStringMixin,
InvenTreeMetadataMixin,
InvenTreeTree,
):
"""Organization tree for StockItem objects.
@@ -438,16 +445,15 @@ STOCK_SORT_DEFAULT = StockSortOrder.DATE_OLDEST
class StockItem(
InvenTree.models.InvenTreeAuditMixin,
InvenTree.models.InvenTreeAttachmentMixin,
InvenTree.models.InvenTreeBarcodeMixin,
InvenTree.models.InvenTreeNoteMixin,
InvenTree.models.InvenTreeTagsMixin,
InvenTreeAuditMixin,
InvenTreeAttachmentMixin,
InvenTreeBarcodeMixin,
InvenTreeNoteMixin,
InvenTreeTagsMixin,
StatusCodeMixin,
report.mixins.InvenTreeReportMixin,
common.models.MetaMixin,
InvenTree.models.MetadataMixin,
InvenTree.models.InvenTreeModel,
InvenTreeMetadataModel,
):
"""A StockItem object represents a quantity of physical instances of a part.
@@ -3720,7 +3726,7 @@ def rename_stock_item_test_result_attachment(instance, filename):
)
class StockItemTestResult(InvenTree.models.InvenTreeMetadataModel):
class StockItemTestResult(InvenTreeMetadataModel):
"""A StockItemTestResult records results of custom tests against individual StockItem objects.
This is useful for tracking unit acceptance tests, and particularly useful when integrated
+4 -4
View File
@@ -27,8 +27,8 @@ from allauth.account.signals import password_reset
from rest_framework.authtoken.models import Token as AuthToken
import InvenTree.helpers
import InvenTree.models
from common.settings import get_global_setting
from generic.models.modelmixins import InvenTreeMetadataMixin
from InvenTree.ready import isImportingData, isReadOnlyCommand
from web.tips import KNOWN_IDS
@@ -90,7 +90,7 @@ def default_token_expiry():
return InvenTree.helpers.current_date() + datetime.timedelta(days=365)
class ApiToken(AuthToken, InvenTree.models.MetadataMixin):
class ApiToken(AuthToken, InvenTreeMetadataMixin):
"""Extends the default token model provided by djangorestframework.authtoken.
Extensions:
@@ -731,7 +731,7 @@ def create_missing_rule_sets(sender, instance, **kwargs):
update_group_roles(instance)
class UserProfile(InvenTree.models.MetadataMixin):
class UserProfile(InvenTreeMetadataMixin):
"""Model to store additional user profile information."""
class UserType(models.TextChoices):
@@ -863,7 +863,7 @@ def create_or_update_user_profile(sender, instance, created, **kwargs):
instance.profile.save()
class TipResult(InvenTree.models.MetadataMixin):
class TipResult(InvenTreeMetadataMixin):
"""Model representing a tip result."""
class Meta: