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)

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 None values 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)

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 None values 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)

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.

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)

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.

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 as None.

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)

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 None values returned as empty strings.

class import_export.widgets.BooleanWidget(coerce_to_string=True)

Widget for converting boolean fields.

The widget assumes that True, False, and None are 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 set null=True on that Django field.

While the BooleanWidget is set up to accept as input common variations of “True” and “False” (and “None”), you may need to munge less common values to True/False/None. Probably the easiest way to do this is to override the before_import_row() function of your Resource class. A short example:

from import_export import fields, resources, widgets

class BooleanExample(resources.ModelResource):
    warn = fields.Field(widget=widgets.BooleanWidget())

    def before_import_row(self, row, **kwargs):
        if "warn" in row.keys():
            # munge "warn" to "True"
            if row["warn"] in ["warn", "WARN"]:
                row["warn"] = True

        return super().before_import_row(row, **kwargs)
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)
Returns:

True is represented as 1, False as 0, and None/NULL as an empty string.

If coerce_to_string is False, the python Boolean type is returned (may be None).

class import_export.widgets.DateWidget(format=None, coerce_to_string=True)

Widget for converting date fields.

Takes optional format parameter. If none is set, either settings.DATE_INPUT_FORMATS or "%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)
Returns:

A python date instance.

Raises:

ValueError if the value cannot be parsed using defined formats.

render(value, obj=None)

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 None values returned as empty strings.

class import_export.widgets.TimeWidget(format=None, coerce_to_string=True)

Widget for converting time fields.

Takes optional format parameter. If none is set, either settings.DATETIME_INPUT_FORMATS or "%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)

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 None values returned as empty strings.

class import_export.widgets.DateTimeWidget(format=None, coerce_to_string=True)

Widget for converting date fields.

Takes optional format parameter. If none is set, either settings.DATETIME_INPUT_FORMATS or "%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)

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 None values 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)

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 None values returned as empty strings.

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)

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)
Returns:

A JSON formatted string derived from value. coerce_to_string has 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 ForeignKey field 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 ForeignKeyWidget has 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 ForeignKeyWidget to lookup related objects using Author.name instead of Author.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. None can 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:

ObjectDoesNotExist if 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)
Returns:

A string representation of the related value. If use_natural_foreign_keys, the value’s natural key is returned. coerce_to_string has no effect on the return value.

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)

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)
Returns:

A string with values separated by separator. None values are returned as empty strings. coerce_to_string has no effect on the return value.