A Widget takes care of converting between import and export representations.
This is achieved by the two methods, clean() and render().
clean(value, row=None, *args, **kwargs)
Returns an appropriate Python object for an imported value.
For example, if you import a value from a spreadsheet, clean() handles conversion of this value into the corresponding Python object.
Numbers or dates can be cleaned to their respective data types and don’t have to be imported as Strings.
render(value, obj=None)
Returns an export representation of a Python value.
For example, if you have an object you want to export, render() takes care of converting the object’s field to a value that can be written to a spreadsheet.
The different types of available widgets are:
import_export.widgets.IntegerWidget
import_export.widgets.DecimalWidget
import_export.widgets.CharWidget
import_export.widgets.BooleanWidget
import_export.widgets.DateWidget
import_export.widgets.TimeWidget
import_export.widgets.DateTimeWidget
import_export.widgets.DurationWidget
import_export.widgets.JSONWidget
import_export.widgets.ForeignKeyWidget
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.
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',)
References:
https://django-import-export.readthedocs.io/en/latest/api_widgets.html
No comments:
Post a Comment