0
class AccountResource(resources.ModelResource):

class Meta:
    model = Account
    skip_unchanged = True
    report_skipped = False
    import_id_fields = ('ID',)
    fields = ('ID', 'Rank_Test', 'UName', 'DecimalTest')

Hello folks the above code is what I am using as my model resource for django-import-export. What I am trying to accomplish is that on import the 'DecimalTest' field uses the django-import-export decimal widget; this is because excel spits out all ints as a float. I am just unsure of how to apply the widget to the DecimalTest field in this context. Any help would be greatly appreciated.

CodeHard
  • 125
  • 14

1 Answers1

1

There is some problems when compare float value between 0.111 and 0.1110 when using DecimalWidget of import_export. So I redefine a custom DecimalWidget.

from django.db.backends import utils
from import_export import widgets
class CustomDecimalWidget(widgets.DecimalWidget):+
    DECIMAL_MAX_DIGITS = 8
    DECIMAL_MAX_PLACES = 2
    def clean(self, value, row=None, *args, **kwargs):
        if self.is_empty(value):
            return None
        return utils.format_number(value, self.DECIMAL_MAX_DIGITS, self.DECIMAL_MAX_PLACES)

Then modify widget of fields.Field class and assign to DecimalTest.

from import_export import fields
class AccountResource(resources.ModelResource):
    DecimalTest = fields.Field(
        column_name='DecimalTest', attribute='DecimalTest', widget=CustomDecimalWidget())
    class Meta:
        model = Account
        skip_unchanged = True
        report_skipped = False
        import_id_fields = ('ID',)
        fields = ('ID', 'Rank_Test', 'UName', 'DecimalTest')
Jak Liao
  • 146
  • 1
  • 5