Django 导入导出选择字段

Django import-export choices field(Django 导入导出选择字段)

本文介绍了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')
    )

这篇关于Django 导入导出选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Django 导入导出选择字段

基础教程推荐