django-excel icon indicating copy to clipboard operation
django-excel copied to clipboard

Import related models without static foreign keys

Open rez0n opened this issue 4 years ago • 4 comments

Hi, I need to import two related sheets without static foreign in the database. Referring to an example from the docs my "Question" sheet always needs to be appended to the database with auto-id and "Choice" rows need to be foreign to the Question using rel_id (but not write rel_id to the database, it is needed only for build relations during import. As a result, the single Question unique field is id that created automatically by database auto increment.

image image

Thanks for any suggestions.

rez0n avatar Mar 04 '21 12:03 rez0n

I've created this logic using plain pyexcel, but not sure how to obtain id of created question object to the choice_func using django-excel

        questions = pyexcel.get_sheet(
            file_name="sample-data.xls", name_columns_by_row=0, sheet_name='question')
        choices = pyexcel.get_sheet(
            file_name="sample-data.xls", name_columns_by_row=0, sheet_name='choice')

        for i in questions:
            obj = Question.objects.create(
                question_text=i[0],
                pub_date=i[1]

            )
            for c in choices:
                if c[4] == i[3]:
                    Choice.objects.create(
                        choice_text=c[1],
                        votes=c[3],
                        question=obj
                    )

rez0n avatar Mar 04 '21 15:03 rez0n

can you query it from django? https://github.com/pyexcel-webwares/django-excel/blob/master/polls/views.py#L76

chfw avatar Mar 07 '21 20:03 chfw

if you use bulk creation, so that won't be possible. hence, you may want to do both in separate process.

chfw avatar Mar 07 '21 20:03 chfw

Hi, it can't be queried from the database because at this moment question not yet created, but when it will be created it will get auto-increment ID and no known pk will be available. The single available pk it is rel_id that accessible only during import, this field not will be imported to the database.

rez0n avatar Mar 07 '21 22:03 rez0n