django-import-export resource definition for foreignkey field?

烈酒焚心 提交于 2019-12-11 20:49:21

问题


Given these models:

class Company(models.Model):
    company_name = models.CharField(max_length=50, unique=True)
    ....

class Product(models.Model):
    company = models.ForeignKey(Company)
    product_name = models.CharField(max_length=100)
    ...

class Inventory(models.Model):
    product = models.ForeignKey(Product, null=True, unique=True)
    ...

Importing from an XLS into Inventory with company_name and product_name properly specified, that is the XLS file contains a single row specifing the company_name and product_name for a unique Product.

The product object can be found in Django/python by::

Product.objects.filter(company__company_name=company_name, product_name=product_name)

How should the Django-import-export resources.ModelResources be constructed to support import via the admin?


回答1:


In your Admin.py use this code.

from import_export.admin import ImportExportModelAdmin,ExportMixin
from import_export import fields,widgets
from import_export import resources
from django.contrib.admin import DateFieldListFilter
class ProductResource(resources.ModelResource):
    def export(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()
        headers = self.get_export_headers()
        data = tablib.Dataset(headers=headers)
        for obj in queryset.iterator():
                data.append(self.export_resource(obj))
        return data

class Meta:
    model = Product

class ProductAdmin(ImportExportModelAdmin):
    resource_class = ProductResource
    list_filter = ('product_name','company__company_name')
    list_display = ('....','....','...')

admin.site.register(Product,ProductAdmin)

for further refrence use https://django-import-export.readthedocs.org/en/latest/installation.html



来源:https://stackoverflow.com/questions/20830921/django-import-export-resource-definition-for-foreignkey-field

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