简体   繁体   English

Django 进出口选择字段

[英]Django import-export choices field

I have a model with choices list ( models.py ):我有一个带有选择列表 ( models.py ) 的 model:

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 ):我还添加了一个新的 class 用于导出所需的字段( 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?我怎样才能通过 Django export获得PRODUCT_SIZE_CHOICES的命名值?

You can use 'get_FOO_display' to achieve this in the Django Admin:您可以在 Django 管理中使用“get_FOO_display”来实现这一点:

class ProductReportResource(resources.ModelResource):
    product_size = fields.Field(
        attribute='get_product_size_display',
        column_name=_(u'Product Size')
    )

In my case I was trying to get the display from a foreign key choice field, like: user__gender在我的例子中,我试图从外键选择字段中获取显示,例如: user__gender

After unsuccessfully trying the accepted answer and the other answer by Waket, I found this thread here: https://github.com/django-import-export/django-import-export/issues/525在尝试接受的答案和 Waket 的其他答案失败后,我在这里找到了这个线程: https://github.com/django-import-export/django-import-export/issues/525

From where I tried a couple of options, and the one that finally worked for me is this:从那里我尝试了几个选项,最终对我有用的是:

  1. Create the widget somewhere在某处创建小部件
from import_export.widgets import Widget

class ChoicesWidget(Widget):
    """
    Widget that uses choice display values in place of database values
    """
    def __init__(self, choices, *args, **kwargs):
        """
        Creates a self.choices dict with a key, display value, and value,
        db value, e.g. {'Chocolate': 'CHOC'}
        """
        self.choices = dict(choices)
        self.revert_choices = dict((v, k) for k, v in self.choices.items())

    def clean(self, value, row=None, *args, **kwargs):
        """Returns the db value given the display value"""
        return self.revert_choices.get(value, value) if value else None

    def render(self, value, obj=None):
        """Returns the display value given the db value"""
        return self.choices.get(value, '')
  1. In your model resource declare the field using the widget and passing the choices to it, like this:在您的 model 资源中,使用小部件声明字段并将选项传递给它,如下所示:
    user__gender = Field(
        widget=ChoicesWidget(settings.GENDER_CHOICES),
        attribute='user__gender',
        column_name="Gènere",
    )

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM