Support importing tags via the data importer (#13418)

- Include writable optional serializer fields (such as "tags") when
  importing data, so that they are available for column mapping
- Stop excluding tag fields from the importable fields
- Convert imported tag values from a comma-separated list
- Report tag fields with the "tags" type in OPTIONS responses, so the
  importer table and row edit form can display them
- Document tag import
This commit is contained in:
Syogo-Suganoya authored and GitHub committed 2026-12-01 15:26:40 +11:00
1 parent 819231c342
commit 449e1117d1
8 files changed
+112 -9

No files matched your search

+4
View File
@@ -35,6 +35,10 @@ Some models allow for mapping based on other "natural key" fields (e.g. the `ref
!!! warning "Unique Identifiers"
If a unique identifier cannot be determined for any related field, the user must manually map the relevant field to the correct existing record in the database, during the import process.
### Tags
For models which support tags, the *Tags* field can be imported as a comma-separated list of tag names (e.g. `tag1, tag2, tag3`). Any tags which do not already exist are created automatically.
## Import Session
Importing data is a multi-step process, which is managed via an *import session*. An import session is created when the user initiates a data import, and is used to track the progress of the data import process.
@@ -1,11 +1,15 @@
"""InvenTree API version information."""
# InvenTree API version
INVENTREE_API_VERSION = 586
INVENTREE_API_VERSION = 587
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
INVENTREE_API_TEXT = """
v587 -> 2026-11-30 : https://github.com/inventree/InvenTree/pull/13418
- "tags" fields are now reported with the "tags" type (instead of "list") in OPTIONS responses
- "tags" fields can now be imported via the data importer (as a comma-separated list)
v586 -> 2026-11-29 : https://github.com/inventree/InvenTree/pull/13410
- Stock, build and order "action" endpoints now require the correct user role action (e.g. "change") rather than "add"
- Deleting build outputs now requires the "build.delete" role
@@ -10,6 +10,7 @@ from rest_framework.fields import empty
from rest_framework.metadata import SimpleMetadata
from rest_framework.request import clone_request
from rest_framework.utils import model_meta
from taggit.serializers import TagListSerializerField
import common.models
import InvenTree.permissions
@@ -664,3 +665,4 @@ class InvenTreeMetadata(SimpleMetadata):
InvenTreeMetadata.label_lookup[DependentField] = 'dependent field'
InvenTreeMetadata.label_lookup[serializers.JSONField] = 'json'
InvenTreeMetadata.label_lookup[TagListSerializerField] = 'tags'
@@ -121,6 +121,20 @@ class FilterableSerializerMixin:
"""Determine if we are exporting data."""
return getattr(self, '_exporting_data', False)
def is_importing(self, kwargs: dict) -> bool:
"""Determine if the serializer is being constructed for data import.
This is the case if the 'importing' flag is provided either as a keyword argument
(when determining the importable fields) or via the serializer context
(when validating imported data).
"""
if getattr(self, '_is_importing', False):
return True
context = kwargs.get('context') or {}
return bool(kwargs.get('importing') or context.get('importing'))
def is_field_included(
self, field_name: str, field: OptionalField, kwargs: dict
) -> bool:
@@ -175,6 +189,10 @@ class FilterableSerializerMixin:
field_kwargs = field.serializer_kwargs or {}
# When importing data, any writable optional fields (e.g. 'tags') are available
if self.is_importing(kwargs) and not field_kwargs.get('read_only', False):
return self.check_field_permission(field, True)
# Skip filtering for a write request
# All fields should be present for data creation,
# excepting those for which the user does not have the required permissions
-6
View File
@@ -1,7 +1,6 @@
"""Mixin classes for data import/export functionality."""
from rest_framework import fields, serializers
from taggit.serializers import TagListSerializerField
import InvenTree.serializers
@@ -85,11 +84,6 @@ class DataImportSerializerMixin:
if issubclass(field.__class__, fields.FileField):
continue
# Skip tags fields
# TODO: Implement tag field import support
if issubclass(field.__class__, TagListSerializerField):
continue
importable_fields[name] = field
return importable_fields
+16 -1
View File
@@ -802,6 +802,8 @@ class DataImportRow(models.Model):
value = InvenTree.helpers.str2bool(value)
elif field_type == 'date':
value = self.convert_date_field(value)
elif field_type == 'tags':
value = self.convert_tags_field(value)
elif field_type == 'related field':
try:
value = self.lookup_related_field(
@@ -861,6 +863,19 @@ class DataImportRow(models.Model):
if commit:
self.save()
def convert_tags_field(self, value) -> list[str]:
"""Convert an imported value into a list of tags.
Tags are provided as a comma-separated string (e.g. "tag1, tag2"),
which is how they are handled internally.
"""
if value is None:
return []
items = value if isinstance(value, (list, tuple)) else str(value).split(',')
return [str(item).strip() for item in items if str(item).strip()]
def convert_date_field(self, value) -> Optional[str]:
"""Convert an incoming date field to the correct format for the database.
@@ -1033,7 +1048,7 @@ class DataImportRow(models.Model):
# back to the existing value on the record, not fail validation
# or be overwritten with a blank/default value
partial=instance is not None,
context={'request': request},
context={'request': request, 'importing': True},
)
def _get_update_instance(self, instance_id, queryset):
+59 -1
View File
@@ -45,7 +45,8 @@ class ImporterTest(ImporterMixin, InvenTreeTestCase):
session.extract_columns()
self.assertEqual(session.column_mappings.count(), 14)
# One mapping for each importable field (including 'tags')
self.assertEqual(session.column_mappings.count(), 15)
# Check some of the field mappings
for field, col in [
@@ -167,6 +168,63 @@ class ImporterTest(ImporterMixin, InvenTreeTestCase):
]:
self.assertEqual(row.convert_date_field(value), expected, msg=value)
def test_convert_tags_field(self):
"""Test conversion of tag values for import."""
row = DataImportRow(row_index=0, row_data={})
for value, expected in [
(None, []),
('', []),
(' ', []),
('alpha', ['alpha']),
('alpha,beta', ['alpha', 'beta']),
(' alpha , beta ,, ', ['alpha', 'beta']),
(['alpha', ' beta '], ['alpha', 'beta']),
(123, ['123']),
]:
self.assertEqual(row.convert_tags_field(value), expected, msg=value)
def test_import_tags(self):
"""Test that the 'tags' field can be imported from a comma-separated list."""
from company.models import Company
data = '\n'.join([
'Company name,Company description,Tags',
'Tagged company,First company,"alpha, beta"',
'Single tag company,Second company,gamma',
'Untagged company,Third company,',
])
session = DataImportSession.objects.create(
data_file=ContentFile(data, 'tags.csv'), model_type='company'
)
# The tags field is available for import
fields = session.available_fields()
self.assertIn('tags', fields)
self.assertEqual(fields['tags']['type'], 'tags')
session.extract_columns()
self.assertTrue(
session.column_mappings.filter(field='tags', column='Tags').exists()
)
session.import_data()
self.assertEqual(session.rows.count(), 3)
for row in session.rows.all():
self.assertTrue(row.valid, msg=row.errors)
row.validate(commit=True)
self.assertTrue(row.complete)
def tags(name):
return sorted(Company.objects.get(name=name).tags.names())
self.assertEqual(tags('Tagged company'), ['alpha', 'beta'])
self.assertEqual(tags('Single tag company'), ['gamma'])
self.assertEqual(tags('Untagged company'), [])
def test_import_header_whitespace(self):
"""Test that column headers with leading/trailing whitespace are handled correctly.
@@ -88,6 +88,14 @@ function ImporterDataCell({
);
}
break;
case 'tags': {
const tags = row.data[column.field];
if (Array.isArray(tags)) {
return tags.length > 0 ? tags.join(', ') : '-';
}
break;
}
default:
break;
}