djangocsvdjango-modelsdjango-forms

What's the easiest way to Import a CSV file into a Django Model?


I am making an app in DJANGO that deals with a lot of 'questions'. There is a question table specified in Model and there will be more or less thousand of questions.

Now, I have an excel file in hand where all the questions are and I can make a CSV file from there. I just need to get the CSV data in my question table. What could be the possible easiest way to do that? Can anyone tell about any tool, process, code to do so?


Solution

  • I do it with a view using csv module. Here is an example of how I create bulk amount of users. This may not be the most efficient way to do it but it sure gets the job done.

    import csv
    from django.contrib.auth.hashers import make_password
    
    def create_bulk_user(request):
        with open(os.path.join(settings.BASE_DIR, 'media', 'core', 'employees.csv')) as f:
            reader = csv.reader(f)
            for row in reader:
                user, created = User.objects.get_or_create(
                    username=str(row[0]),
    
                    defaults={
                        'password': make_password('ddff123#'),
                        'first_name': ' '.join(row[1].split()[:-1]),
                        'last_name': str(row[1].split()[-1])
                    }
                )
                designation, created = Designation.objects.get_or_create(
                    name=str(row[4]), defaults={}
                )
                department, created = Department.objects.get_or_create(
                    name=str(row[3])
                )
                user.profile.designation = designation
                user.profile.department = department
                user.profile.proximity_id = str(row[2])
                user.profile.save()
    
        context = {}
        return render(request, "core/create_bulk_user.html", context)
    

    Keep in mind that there is a bulk_create method for you to use but I haven't used that over here.