我有一个带有选择列表的模型(models.py
):
class Product(models.Model):
...
UNITS_L = 1
UNITS_SL = 2
UNITS_XL = 3
PRODUCT_SIZE_CHOICES = (
(UNITS_L, _('L')),
(UNITS_SL, _('SL')),
(UNITS_XL), _('XL'),
)
product_size = models.IntegerField(choices=PRODUCT_SIZE_CHOICES)
...
我还添加了一个用于导出所需字段的新类(admin.py
):
from import_export import resources, fields
...
Class ProductReport(resources.ModelResource):
product_size = fields.Field()
class Meta:
model = Product
#I want to do a proper function to render a PRODUCT_SIZE_CHOICES(product_size)
def dehydrate_size_units(self, product):
return '%s' % (product.PRODUCT_SIZE_CHOICES[product_size])
fields = ('product_name', 'product_size')
Class ProductAdmin(ExportMixin, admin.ModelAdmin):
resource_class = ProductReport
但这不起作用。如何通过Django import-export在PRODUCT_SIZE_CHOICES
中获得export
的命名值?
答案 0 :(得分:2)
您可以使用'get_FOO_display'在Django Admin中实现此目的:
class ProductReportResource(resources.ModelResource):
product_size = fields.Field(
attribute='get_product_size_display',
column_name=_(u'Product Size')
)
答案 1 :(得分:0)
另一种解决方案:
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):
...