Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a script to insert data in my default sqlite3 database django

I have defined my model and all in Django and if a user is registering via my application the user is well register in the database. The problem is I have a file containing a JSON with plenty of users. I want to do a job that allow me to read this file and insert all the user in my database.

What is the best way to do it? How to connect to the Database without using Django?

like image 975
mel Avatar asked Mar 11 '23 05:03

mel


1 Answers

Why do you want to connect to the database without Django? I would do it using Django, but you need to initialize Django, to be able to run scripts against it. Something like this should do it:

import os, sys
sys.path.append('/path/to/django/project')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.settings'
import django
django.setup()
from django.contrib.auth.models import User

for row in data:
    user = User.objects.create_user(username=row['username'])

/path/to/django/project is the path to the folder where the directory containing your settings is. For example with hierarchy of:

/projects/my_project
/projects/my_project/my_app
/projects/my_project/my_project/setting.py

you you need to append /projects/my_project.

If instead of the Django User model you need to work with a custom model, instead of

from django.contrib.auth.models import User

do

from app_name.models import ModelName
like image 176
skoll Avatar answered Apr 08 '23 00:04

skoll