Django 导入导出选择字段
问题描述
我有一个带有选择列表的模型 (models.py
):
I have a model with choices list (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
):
Also I added a new class for exporting needed fields(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 在 export
中获取 PRODUCT_SIZE_CHOICES
的命名值?
But this is not working. How can I get a named value of PRODUCT_SIZE_CHOICES
in export
by Django import-export ?
解决方案
您可以在 Django Admin 中使用 'get_FOO_display' 来实现:
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')
)
相关文章