Fxs7576
Fxs7576

Reputation: 1341

Django import_export error in exporting with foreignkey

I am trying to import a data set using import_export. There in one column in the data set that is based on the foreignkey (by actual "item_sku" value, rather by its "id") from another model. However, it keeps giving me the following error:

"Line number: 1 - Model_Model01 matching query does not exist. "

How can I fix this? I have been referring to the following sources: source 01 and source 02, but the issue still persists.

Here are my codes:

Models.py

from django.db import models

class Model_Model01(models.Model):

    item_sku = models.CharField(max_length = 2, null = False, blank = False)

    def __unicode__(self):
        return self.item_sku

class Model_Model02(models.Model):

    item_sku = models.ForeignKey(Model_Model01, on_delete = models.CASCADE, null = True, blank = False)

    def __unicode__(self):
        return self.item_sku

admin.py

from import_export import fields
from import_export.admin import ImportExportModelAdmin
from import_export.widgets import ForeignKeyWidget
from .models import (Model_Model01, Model_Model02)


class Admin_Model02(ImportExportModelAdmin):

    item_sku = fields.Field(
        column_name = "item_sku",
        attribute = "item_sku",
        widget = ForeignKeyWidget(Model_Model01, "item_sku")
        )

    class Meta:
        model = Model_Model02

admin.site.register(Model_Model02, Admin_Model02)

Upvotes: 0

Views: 915

Answers (1)

kagronick
kagronick

Reputation: 2688

You need to make a resource object in your admin. It has an import_id_field parameter that defines what the primary key should be.

Here is the example from the documentation:

from import_export import resources
from import_export.admin import ImportExportModelAdmin
from .models import Book    

class BookResource(resources.ModelResource):

    class Meta:
        model = Book
        import_id_fields = ('isbn',)
        fields = ('isbn', 'name', 'author', 'price',)

class BookAdmin(ImportExportModelAdmin):
    resource_class = BookResource

Upvotes: 1

Related Questions