简体   繁体   中英

Django import-export fields

I have a short question about django-import-export. In my model I have choice list:

STATE_CHOICES = ((NEW_STATE, u'New'),
                 (DELIVERED_STATE, u'Delivered'),          
                 (LOST_STATE, u'Lost'),

And method that handles mapping choices for names

@staticmethod
def get_status_name_by_status(status):
    return next((s[1] for s in MyModel.STATE_CHOICES if s[0] == status), 'Uknown')

I want to import/export some data

class MyModelResource(resources.ModelResource):
    status = fields.Field(column_name='status', attribute='order',
                          widget=ForeignKeyWidget(Order, 'status'))

I want to use my get_status_name_by_status method so the choices will be converted to names. But there is no possibility to use method here, only fields are allowed. Any tip how this can be done ?

You can use 'get_FOO_display' to achieve this in the Django Admin:

class MyModelResource(resources.ModelResource):
    status = fields.Field(
        attribute='get_status_display',
        column_name=_(u'Status')
    )

A hack method to realize this quickly, just configure _choice_fields to your choices fields, that's it.

import import_export
from import_export import resources


class MyModelResource(resources.ModelResource):
    _choice_fields = [
        'field_a', 'field_b',
    ]
    for _field_name in _choice_fields:
        locals()[_field_name] = import_export.fields.Field(
            attribute='get_%s_display' % _field_name,
            column_name=MyModel._meta.get_field(_field_name).verbose_name
        )

if you want import and export having different field inside Django import-export.

class CommonResourcesClass(resources.ModelResource):
    class Meta:
        model = Model
        fields = None

class ExportResourcesClass(resources.ModelResource):
    class Meta:
        model = Model
        fields = None

class ModelAdmin(ImportExportModelAdmin, ImportExportActionModelAdmin):
    list_display = ()
    resource_class = CommonResourcesClass
    def get_export_resource_class(self):
        return ExportResourcesClass

Not all data can be easily extracted from an object/model attribute. In order to turn complicated data model into a (generally simpler) processed data structure, dehydrate_fieldname method should be defined:

class MyModelResource(resources.ModelResource):
    status_name = fields.Field()

    def dehydrate_status_name(self, myModel):
        MyModel.get_status_name_by_status(myModel.status)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM