Widgets
- class import_export.widgets.Widget(coerce_to_string=True)
A Widget handles converting between import and export representations.
- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
Returns an appropriate python object for an imported value. For example, a date string will be converted to a python datetime instance.
- Parameters:
value – The value to be converted to a native type.
row – A dict containing row key/value pairs.
**kwargs –
Optional kwargs.
- render(value, obj=None, **kwargs)
Returns an export representation of a python value.
- Parameters:
value – The python value to be rendered.
obj – The model instance from which the value is taken. This parameter is deprecated and will be removed in a future release.
- Returns:
By default, this value will be a string, with
Nonevalues returned as empty strings.
- class import_export.widgets.NumberWidget(coerce_to_string=True)
Widget for converting numeric fields.
- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- render(value, obj=None, **kwargs)
Returns an export representation of a python value.
- Parameters:
value – The python value to be rendered.
obj – The model instance from which the value is taken. This parameter is deprecated and will be removed in a future release.
- Returns:
By default, this value will be a string, with
Nonevalues returned as empty strings.
- class import_export.widgets.IntegerWidget(coerce_to_string=True)
Widget for converting integer fields.
- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
Converts the input value to a Python integer.
Uses Decimal for precise conversion to handle locale-specific number formatting.
- Parameters:
value – The value to be converted to integer. Can be a string or numeric type.
row – The current row being processed.
**kwargs –
Optional keyword arguments.
- Returns:
A Python int instance, or None if value is empty.
- Raises:
ValueError – If the value cannot be converted to integer.
InvalidOperation – If Decimal conversion fails.
- class import_export.widgets.DecimalWidget(coerce_to_string=True)
Widget for converting decimal fields.
- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
Converts the input value to a Python Decimal for precise numeric operations.
- Parameters:
value – The value to be converted to Decimal. Can be a string or numeric type.
row – The current row being processed.
**kwargs –
Optional keyword arguments.
- Returns:
A Python Decimal instance, or None if value is empty.
- Raises:
InvalidOperation – If the value cannot be converted to Decimal.
- class import_export.widgets.CharWidget(coerce_to_string=True, allow_blank=True)
Widget for converting text fields.
- Parameters:
allow_blank – If True, then
clean()will return null values as empty strings, otherwise asNone.
- clean(value, row=None, **kwargs)
Converts the input value to a string, handling None values based on allow_blank setting.
- Parameters:
value – The value to be converted to string.
row – The current row being processed.
**kwargs –
Optional keyword arguments.
- Returns:
A string representation of the value. Returns empty string if value is None and
allow_blankis True, otherwise returns None.
- render(value, obj=None, **kwargs)
Returns an export representation of a python value.
- Parameters:
value – The python value to be rendered.
obj – The model instance from which the value is taken. This parameter is deprecated and will be removed in a future release.
- Returns:
By default, this value will be a string, with
Nonevalues returned as empty strings.
- class import_export.widgets.BooleanWidget(coerce_to_string=True)
Widget for converting boolean fields.
The widget assumes that
True,False, andNoneare all valid values, as to match Django’s BooleanField. That said, whether the database/Django will actually accept NULL values will depend on if you have setnull=Trueon that Django field.Recognizes standard boolean representations. For custom boolean values, see Custom Boolean value handling in the advanced usage documentation.
- clean(value, row=None, **kwargs)
Converts the input value to a Python boolean or None.
Recognizes common string representations of boolean values: - True values: ‘1’, 1, True, ‘true’, ‘TRUE’, ‘True’ - False values: ‘0’, 0, False, ‘false’, ‘FALSE’, ‘False’ - Null values: ‘’, None, ‘null’, ‘NULL’, ‘none’, ‘NONE’, ‘None’
- Parameters:
value – The value to be converted to boolean.
row – The current row being processed.
**kwargs –
Optional keyword arguments.
- Returns:
True, False, or None depending on the input value.
- render(value, obj=None, **kwargs)
- Returns:
Trueis represented as1,Falseas0, andNone/NULL as an empty string.If
coerce_to_stringisFalse, the python Boolean type is returned (may beNone).
- class import_export.widgets.DateWidget(format=None, coerce_to_string=True)
Widget for converting date fields to Python date instances.
Takes optional
formatparameter. If none is set, eithersettings.DATE_INPUT_FORMATSor"%Y-%m-%d"is used.- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
Converts a date string to a Python date instance using configured formats.
Attempts to parse the value using formats specified during widget initialization. If no format was provided, uses
settings.DATE_INPUT_FORMATSor “%Y-%m-%d”.- Parameters:
value – A date string to be parsed, or an existing date instance.
row – The current row being processed.
**kwargs –
Optional keyword arguments.
- Returns:
A Python date instance, or None if value is empty.
- Raises:
ValueError – If the value cannot be parsed using any of the defined formats.
- render(value, obj=None, **kwargs)
Returns an export representation of a python value.
- Parameters:
value – The python value to be rendered.
obj – The model instance from which the value is taken. This parameter is deprecated and will be removed in a future release.
- Returns:
By default, this value will be a string, with
Nonevalues returned as empty strings.
- class import_export.widgets.TimeWidget(format=None, coerce_to_string=True)
Widget for converting time fields.
Takes optional
formatparameter. If none is set, eithersettings.DATETIME_INPUT_FORMATSor"%H:%M:%S"is used.- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
- Returns:
A python time instance.
- Raises:
ValueError if the value cannot be parsed using defined formats.
- render(value, obj=None, **kwargs)
Returns an export representation of a python value.
- Parameters:
value – The python value to be rendered.
obj – The model instance from which the value is taken. This parameter is deprecated and will be removed in a future release.
- Returns:
By default, this value will be a string, with
Nonevalues returned as empty strings.
- class import_export.widgets.DateTimeWidget(format=None, coerce_to_string=True)
Widget for converting datetime fields to Python datetime instances.
Takes optional
formatparameter. If none is set, eithersettings.DATETIME_INPUT_FORMATSor"%Y-%m-%d %H:%M:%S"is used.- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
- Returns:
A python datetime instance.
- Raises:
ValueError if the value cannot be parsed using defined formats.
- render(value, obj=None, **kwargs)
Returns an export representation of a python value.
- Parameters:
value – The python value to be rendered.
obj – The model instance from which the value is taken. This parameter is deprecated and will be removed in a future release.
- Returns:
By default, this value will be a string, with
Nonevalues returned as empty strings.
- class import_export.widgets.DurationWidget(coerce_to_string=True)
Widget for converting time duration fields.
- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
- Returns:
A python duration instance.
- Raises:
ValueError if the value cannot be parsed.
- render(value, obj=None, **kwargs)
Returns an export representation of a python value.
- Parameters:
value – The python value to be rendered.
obj – The model instance from which the value is taken. This parameter is deprecated and will be removed in a future release.
- Returns:
By default, this value will be a string, with
Nonevalues returned as empty strings.
- class import_export.widgets.SimpleArrayWidget(separator=None, coerce_to_string=True)
Widget for an Array field. Can be used for Postgres’ Array field.
- Parameters:
separator – Defaults to
','coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
Converts a separated string into a Python array.
Splits the input string by the configured separator. Empty strings result in empty arrays rather than arrays containing empty strings.
- Parameters:
value – A string containing values separated by the configured separator.
row – The current row being processed.
**kwargs –
Optional keyword arguments.
- Returns:
A Python list derived from splitting the value by separator. Returns an empty list if value is None or empty.
- render(value, obj=None, **kwargs)
- Returns:
A string with values separated by
separator. Ifcoerce_to_stringisFalse, the native array will be returned. Ifvalueis None, None will be returned ifcoerce_to_stringis
False, otherwise an empty string will be returned.
- class import_export.widgets.JSONWidget(coerce_to_string=True)
Widget for a JSON object (especially required for jsonb fields in PostgreSQL database.)
- Parameters:
value – Defaults to JSON format.
The widget covers two cases: Proper JSON string with double quotes, else it tries to use single quotes and then convert it to proper JSON.
- Parameters:
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
Parses the input value as JSON and returns the corresponding Python object.
Attempts to parse as valid JSON first, then falls back to single-quote format by converting single quotes to double quotes before parsing.
- Parameters:
value – A JSON string to be parsed.
row – The current row being processed.
**kwargs –
Optional keyword arguments.
- Returns:
The parsed Python object (dict, list, etc.) or None if value is empty.
- Raises:
JSONDecodeError – If the value cannot be parsed as JSON.
- render(value, obj=None, **kwargs)
- Returns:
A JSON formatted string derived from
value.coerce_to_stringhas no effect on the return value.
- class import_export.widgets.ForeignKeyWidget(model, field='pk', use_natural_foreign_keys=False, key_is_id=False, **kwargs)
Widget for a
ForeignKeyfield which looks up a related model using either the PK or a user specified field that uniquely identifies the instance in both export and import.The lookup field defaults to using the primary key (
pk) as lookup criterion but can be customized to use any field on the related model.Unlike specifying a related field in your resource like so…
class Meta: fields = ('author__name',)
…using a
ForeignKeyWidgethas the advantage that it can not only be used for exporting, but also importing data with foreign key relationships.Here’s an example on how to use
ForeignKeyWidgetto lookup related objects usingAuthor.nameinstead ofAuthor.pk:from import_export import fields, resources from import_export.widgets import ForeignKeyWidget class BookResource(resources.ModelResource): author = fields.Field( column_name='author', attribute='author', widget=ForeignKeyWidget(Author, 'name')) class Meta: fields = ('author',)
- Parameters:
model – The Model the ForeignKey refers to (required).
field – A field on the related model used for looking up a particular object.
use_natural_foreign_keys – Use natural key functions to identify related object, default to False
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
- Returns:
a single Foreign Key instance derived from the args.
Nonecan be returned if the value passed is a null value.- Parameters:
value – The field’s value in the dataset.
row – The dataset’s current row.
**kwargs – Optional kwargs.
- Raises:
ObjectDoesNotExistif no valid instance can be found.
- get_lookup_kwargs(value, row, **kwargs)
- Returns:
the key value pairs used to identify a model instance. Override this to customize instance lookup.
- Parameters:
value – The field’s value in the dataset.
row – The dataset’s current row.
**kwargs – Optional kwargs.
- get_queryset(value, row, *args, **kwargs)
Returns a queryset of all objects for this Model.
Overwrite this method if you want to limit the pool of objects from which the related object is retrieved.
- Parameters:
value – The field’s value in the dataset.
row – The dataset’s current row.
*args – Optional args.
**kwargs – Optional kwargs.
As an example; if you’d like to have ForeignKeyWidget look up a Person by their pre- and lastname column, you could subclass the widget like so:
class FullNameForeignKeyWidget(ForeignKeyWidget): def get_queryset(self, value, row, *args, **kwargs): return self.model.objects.filter( first_name__iexact=row["first_name"], last_name__iexact=row["last_name"] )
- render(value, obj=None, **kwargs)
- Returns:
A string representation of the related value. If
use_natural_foreign_keys, the value’s natural key is returned.coerce_to_stringhas no effect on the return value.
- class import_export.widgets.CachedForeignKeyWidget(model, field='pk', use_natural_foreign_keys=False, key_is_id=False, **kwargs)
A
ForeignKeyWidgetsubclass that caches the queryset results to minimize database hits during import. The defaultForeignKeyWidgetmakes query for each row, which can be inefficient for large imports. This widget fetches all related instances once and caches them in memory for subsequent lookups.Using this class has some limitations:
It does not support caching when
use_natural_foreign_keys=Trueis set.It calls
get_queryset()only once, so if the queryset depends on the row data, this widget may not work as expected. You must be sure that the queryset is static for all rows. Avoid usingCachedForeignKeyWidgetin the following way:class FullNameForeignKeyWidget(CachedForeignKeyWidget): def get_queryset(self, value, row, *args, **kwargs): return self.model.objects.filter( first_name__iexact=row["first_name"], last_name__iexact=row["last_name"] )
It makes more sense to filter by static values:
class ActiveForeignKeyWidget(CachedForeignKeyWidget): def get_queryset(self, value, row, *args, **kwargs): return self.model.objects.filter(active=True)
It stores data in a hash table where the key is a tuple of the fields that returned by
get_lookup_kwargs(). You must be sure that the lookup fields are the same for all rows. If the lookup fields differ between rows, this widget may not work as expected. The following example is incorrect usage:class MultiColumnForeignKeyWidget(CachedForeignKeyWidget): def get_lookup_kwargs(self, value, row, **kwargs): if row['active'] == 'yes': return {self.field: value, 'active': True} else: return {self.field: value, 'inactive': True}
It performs lookup on Python side, so the filtering logic with non-text data types may not work:
class MultiColumnForeignKeyWidget(CachedForeignKeyWidget): def get_lookup_kwargs(self, value, row, **kwargs): # row['birthday'] is a string like '01-01-2000'. # # It won't match the instance because the birthday values # in the cached instances are datetime objects, not strings. return {self.field: value, 'birthday': row['birthday']}
It does not support complex lookups like
__gt,__lt, or filtering over relationships in theget_lookup_kwargs(). For example, the following code won’t work:class BookForeignKeyWidget(CachedForeignKeyWidget): def get_lookup_kwargs(self, value, row, **kwargs): return {f'{self.field}__author': value}
- Parameters:
model – The Model the ForeignKey refers to (required).
field – A field on the related model used for looking up a particular object.
use_natural_foreign_keys – Use natural key functions to identify related object, default to False
coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- get_lookup_kwargs(value, row, **kwargs)
- Returns:
the key value pairs used to identify a model instance. Override this to customize instance lookup.
- Parameters:
value – The field’s value in the dataset.
row – The dataset’s current row.
**kwargs – Optional kwargs.
- get_queryset(value, row, *args, **kwargs)
Returns a queryset of all objects for this Model.
Overwrite this method if you want to limit the pool of objects from which the related object is retrieved.
- Parameters:
value – The field’s value in the dataset.
row – The dataset’s current row.
*args – Optional args.
**kwargs – Optional kwargs.
As an example; if you’d like to have ForeignKeyWidget look up a Person by their pre- and lastname column, you could subclass the widget like so:
class FullNameForeignKeyWidget(ForeignKeyWidget): def get_queryset(self, value, row, *args, **kwargs): return self.model.objects.filter( first_name__iexact=row["first_name"], last_name__iexact=row["last_name"] )
- class import_export.widgets.ManyToManyWidget(model, separator=None, field=None, **kwargs)
Widget that converts between representations of a ManyToMany relationships as a list and an actual ManyToMany field.
- Parameters:
model – The model the ManyToMany field refers to (required).
separator – Defaults to
','.field – A field on the related model. Default is
pk.coerce_to_string – If True,
render()will return a string representation of the value, otherwise the value is returned.
- clean(value, row=None, **kwargs)
Converts a separated string of values into a QuerySet for ManyToMany relationships.
Splits the input by the configured separator and looks up model instances using the specified field. Filters out empty values after splitting.
- Parameters:
value – String of separated values, or a single numeric value.
row – The current row being processed.
**kwargs –
Optional keyword arguments.
- Returns:
A QuerySet containing the related model instances, or an empty QuerySet if no value provided.
- render(value, obj=None, **kwargs)
- Returns:
A string with values separated by
separator.Nonevalues are returned as empty strings.coerce_to_stringhas no effect on the return value.