yousaf raza
yousaf raza

Reputation: 37

Django importing text file Data Into sqllit3

I have tabulated text files of my data and records are too much in number i cant upload it one by one in database is there any way to import that data into the table i created in model

Upvotes: 2

Views: 961

Answers (1)

Johan
Johan

Reputation: 3611

I have created a simple script that might be a start for you. This script will read in a csv-file and store it into a database. You should be able to modify it to meet your needs by replacing filename.csv to the location of your file, and YourModel to the actual model that it represents. You will also need to change obj.field1 = line[0] to the representing columns and fields that are matched with each other.

import csv

# Open the csv file and reads it into a two dimensional List
with open('filename.csv', 'rb') as f:
    reader = csv.reader(f)
    lines = list(reader)

# Create an empty list of objects of your model
objects = []

# Iterate each record of the csv file
for line in lines:
    # Create an empty instance of your model
    obj = YourModel()
    # Populate the fields of the model based on the record line of your file
    obj.field1 = line[0] # The first column
    obj.field2 = line[1] # The second column
    # Add the model to the list of objects
    objects.append(obj)

# Save all objects simultaniously, instead of saving for each line
YourModel.objects.bulk_create(objects)

Upvotes: 2

Related Questions