Django import-export choices field

梦想的初衷 提交于 2020-01-15 05:18:26

问题


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)
    ...

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

But this is not working. How can I get a named value of PRODUCT_SIZE_CHOICES in export by Django import-export ?


回答1:


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')
    )


来源:https://stackoverflow.com/questions/39674976/django-import-export-choices-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!