问题
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