Working with import foreignKeys in django-import-export

I do not understand how the django-import-export module works with ForeignKeys. Here is a simple example: models.py

class TFamilies(models.Model):
    id_fam = models.AutoField(primary_key=True, unique=True)
    name_fam = models.CharField(max_length=1024, blank=True,verbose_name='Famille')


class TGenus(models.Model):
    id_genus = models.AutoField(primary_key=True, unique=True)
    name_genus = models.CharField(max_length=1024,verbose_name='nom de genre')
    id_fam = models.ForeignKey(TFamilies, null=True, db_column='id_fam', blank=True, verbose_name='Famille')

I would like people to add a kindred lineage! CSV / XLS with the names name_genus and name_fam ... (and id remains empty).

The family already exists in the database most of the time, Django juste must find the correct id number ...

admin.py

class TGenusResource(resources.ModelResource):

    name_fam = fields.Field(widget=widgets.ForeignKeyWidget(TFamilies, 'name_fam'))

    class Meta:
        model = TGenus
        import_id_fields = ['id_genus']


class TGenusAdmin(ImportExportActionModelAdmin):
    form = TGenusAdminForm
    resource_class = TGenusResource
    pass

This configuration results in an error in the import interface:

Line number: 1 - 'NoneType' object has no attribute 'name_fam'
Traceback (most recent call last):
File "/....../lib/python2.7/site-packages/import_export/resources.py", line 348, in import_data
row_result.object_repr = force_text(instance)
File "......./lib/python2.7/site-packages/django/utils/encoding.py", line 85, in force_text
s = six.text_type(s)
AttributeError: 'NoneType' object has no attribute 'name_fam'

I don’t understand ... I also tried to answer there: django-import-export resource definition for foreignkey field? and sort of like: Foreign key in django migration using django-import-export

Do I need to use before_import to find a match?

+2
1

, ! tablib, , , .

excel id_genus (empty), name_genus id_fam, !

, , :

def before_import(self, dataset, dry_run):
        """
        Make standard corrections to the dataset before displaying to user
        """

        i = 0
        last = dataset.height - 1

        # for all lines, search for id of family given and add a new line at the bottom with it then delete the first one
        while i <= last:
            # Check if the Genus exist in DB
            if (TGenus.objects.filter(name_genus=dataset.get_col(2)[0].capitalize())):
                id_genus = TGenus.objects.filter(name_genus=dataset.get_col(2)[0].capitalize())[0].id_genus
            else :
                id_genus = ''
            # Check if the family exists in DB
            try:
                TFamilies.objects.get(name_fam=dataset.get_col(2)[0].capitalize())
            except TFamilies.DoesNotExist:
                raise Exception("Family not in DB !")                   
            except TFamilies.MultipleObjectsReturned:
                pass

            # use of "filter" instead of "get" to prevent duplicate values, select the first one in all cases
            dataset.rpush((id_genus,
                dataset.get_col(1)[0],
                TFamilies.objects.filter(name_fam=dataset.get_col(2)[0].capitalize())[0].id_fam))
            dataset.lpop()
            i = i + 1

django sys-admin, , DB... - , ! , , ... , , : django import-export?

+1

All Articles