2

I have CSV file backed up from my django model with django-import-export,I want to restore that to my model how can i do that ? When i want to create object for each of them i have problem with foreign keys.

id,name,address,job,KBSE
1,Hamid,3,Doctor,4311
2,Ali,7,Artist,5343
3,Reza,2,Singer,5232

3 Answers 3

3

See Import data workflow. Most functions can be overridden in resource subclass. If that does not help, please open issue.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use customized python script using pandas to load csv data into Django model.

#First define your Django Enviromental variables

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoProjectName.settings")
import django
django.setup()
import pandas as pd
import numpy as np

   
#Import Required Django model

from djangoApp.models import * #models

# Import CSV file
df = pd.read_csv('csv_url.csv')

# Do required pre-processing on panda dataframe 
# such as data cleaning, data format settings etc..

# Iterater throught panda dataframe and save data in Django model

for index, row in df.iterrows():

      # create django model

      samplemodelObject = SampleModel()

      # Normal Fields ( Non-foreign key fields) adding
     
      samplemodelObject.field_name01 = row['Field_01']

      
      # Adding Foreign Key Field

       samplemodelObject.field_foreignkey = ForeignKeyModel.objects.get( fk_key = row['fk_value_field']

      # save data model instance
      samplemodelObject.save()
      samplemodelObject.clear()
      

Comments

0

You should import the table in the right order, make sure you import all the data the you depend first.

So load foreign tables and than load the current. If you don't have the foreign data and some of them where erased, you'll have to create it back.

Good luck!

1 Comment

Is there any option on django-import-export to import CSV file to a model and the library handels Foreign key relationship based on model information ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.