如何在django-import-export中进行字段验证

时间:2017-09-04 15:10:39

标签: django django-admin django-import-export

以下是我的模特:

class Product(models.Model):
    product_title = models.CharField(max_length=100, null=False, 
verbose_name='Product title')
    product_description = models.TextField(max_length=250, 
verbose_name='Product description')
    product_qty = models.IntegerField(verbose_name='Quantity')
    product_mrp = models.FloatField(verbose_name='Maximum retail price')
    product_offer_price = models.FloatField(verbose_name='Selling price')

我希望在保存之前对 product_offer_price 字段进行验证,我已经发布了 QUESTION ,并且已通过工作解决方案进行了回答。

需要验证:

 if product_offer_price > product_mrp:
    raise ValidationError

现在上述问题的解决方案非常适用于管理表单。

但是,我已经实现了django-import-export,我在admin中批量导入产品数据,在批量导入期间我需要类似的验证。

如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

嗯,这是一个小小的研究过程。

最后我明白了。

麻烦在于避免导入导出库中的ProductForm。 内部库导入调用实例的save()方法,但是如果我们在Model(不是Form)中使用DEBUG = False引发ValidationError,使用DEBUG = True引发跟踪页面。 所以我们应该在import_export资源中使用“before_import”方法,在django.forms表单中使用“clean”方法。

admin.py

from forms import ProductForm
from models import Product
from import_export import resources
from import_export.admin import ImportExportActionModelAdmin
from django.forms import ValidationError

class ProductResource(resources.ModelResource):

    class Meta:
        model = Product

    def before_import(self, dataset, using_transactions, dry_run, **kwargs):
        for row in dataset:
            if int(row[4]) < int(row[5]):
                raise ValidationError('Product offer price cannot be greater than Product MRP. '
                                      'Error in row with id = %s' % row[0])


class ProductAdmin(ImportExportActionModelAdmin):
    list_display = ('product_title', 'product_description', 'product_qty', 'product_mrp', 'product_offer_price')
    form = ProductForm
    resource_class = ProductResource


admin.site.register(Product, ProductAdmin)

forms.py

from django import forms
from models import Product


class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        exclude = [id, ]

    def clean(self):
        product_offer_price = self.cleaned_data.get('product_offer_price')
        product_mrp = self.cleaned_data.get('product_mrp')
        if product_offer_price > product_mrp:
            raise forms.ValidationError("Product offer price cannot be greater than Product MRP.")
        return self.cleaned_data

models.py

class Product(models.Model):
    product_title = models.CharField(max_length=100, null=False, verbose_name='Product title')
    product_description = models.TextField(max_length=250, verbose_name='Product description')
    product_qty = models.IntegerField(verbose_name='Quantity')
    product_mrp = models.FloatField(verbose_name='Maximum retail price')
    product_offer_price = models.FloatField(verbose_name='Selling price')

答案 1 :(得分:0)

这是Django Rest Framework的另一种简单方法

template <std::size_t N>
using DoubleArray = std::array<double, N>;

int main()
{
   std::map<DoubleArray<2>,double> my_cache;
   my_cache[{12, 2}] = 23;
}

答案 2 :(得分:0)

一种更简单的方法可能是通过向资源类添加自定义before_import_row方法来进入导入/导出工作流程:

class ProductResource(resources.ModelResource):

    class Meta:
        model = Product

    def before_import_row(self, row, **kwargs):
        if int(row[4]) < int(row[5]):
            raise ValidationError('Product offer price cannot be greater than Product MRP. '
                                  'Error in row with id = %s' % row[0])