Django import-export choices field

前端 未结 2 1235
栀梦
栀梦 2021-01-20 15:06

I have a model with choices list (models.py):

class Product(models.Model):
    ...
    UNITS_L = 1
    UNITS_SL = 2
    UNITS_XL = 3
    PRODUCT         


        
相关标签:
2条回答
  • 2021-01-20 15:26

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

    class ProductReportResource(resources.ModelResource):
        product_size = fields.Field(
            attribute='get_product_size_display',
            column_name=_(u'Product Size')
        )
    
    0 讨论(0)
  • 2021-01-20 15:30

    Another solution:

    class BaseModelResource(resources.ModelResource):
    
        def export_field(self, field, obj):
            field_name = self.get_field_name(field)
            func_name = 'get_{}_display'.format(field_name)
            if hasattr(obj, func_name):
                return getattr(obj, func_name)
            return super().export_field(field, obj)
    
    
    class ProductReportResource(BaseModelResource):
        ...
    
    0 讨论(0)
提交回复
热议问题